mongodb like query

MongoDB query to perform a LIKE match – Example

This article explains you how to write a mongo query to perform a LIKE match in MongoDB. Note, MongoDB does not have “LIKE” operator like you have in SQL which can be used in a WHERE clause to search for a specified pattern in a column.

First, let’s insert the following documents in the collection called “posts” for our example

SQL LIKE Syntax

Let’s consider the below SQL LIKE statement used to find all the records where by_user column is like “%s”

Mongo LIKE Query Example

Below is the mongo query to match all the documents where by_user field is like “%s”

> db.posts.find({by_user: {$regex: /s$/}}).pretty()

What is $regex in Mongo?

It provides regular expression capabilities for pattern matching strings in queries. Mongo uses Perl compatible regular expressions (PCRE)

You can use any one of the following syntaxes to use $regex:

$options

The following are the options that are available for use with regular expressions

i – case insensitivity to match upper and lower cases

m – For patterns that include anchors (i.e. ^ for the start and $ for the end)

x – Extended capability to ignore all the white space characters in the $regex pattern

s – Allows the dot (.) character to match all the characters including newline characters.

$regex Vs. /pattern/ Syntax:

$regex has some restrictions for particular syntax use. For example, you cannot use $regex operator expressions inside an $in. So mongo allows you to use regular expressions objects as shown below to specify regular expressions.

Example for $in expressions

> db.posts.find({by_user: { $in: [/^sne/i, /^mon/]}}).pretty()

Syntax:

Try to run the following mongo command and check the ouput

> db.posts.find({by_user: /s/}).pretty()

Further Learning

References

Leave a Reply

avatar
  Subscribe  
Notify of