Home >>MongoDB Tutorial >MongoDB Regular Expression

MongoDB Regular Expression

MongoDB Regular Expression

Regular Expressions are widely used to look for a pattern or word in any string in all languages. MongoDB also offers regular expression functionality for string pattern matching using the operator $regex. As a standard expression language, MongoDB utilizes PCRE (Perl Compatible Regular Expression).

We do not need to do any configuration or command to use regular expressions, unlike text search.

Suppose we have inserted a document as shown below in a database called posts-

> db.posts.insert(
{
   "post_text": "enjoy the mongodb articles on phptpoint",
   "tags": [
      "mongodb",
      "phptpoint"
   ]
}
WriteResult({ "nInserted" : 1 })

Using regex Expression

The regex query below searches for all posts containing the phptpoint string.

> db.posts.find({post_text:{$regex:"phptpoint"}}).pretty()
{
	"_id" : ObjectId("5dd7ce28f1dd4583e7103fe0"),
	"post_text" : "enjoy the mongodb articles on phptpoint",
	"tags" : [
		"mongodb",
		"phptpoint"
	]
}
{
	"_id" : ObjectId("5dd7d111f1dd4583e7103fe2"),
	"post_text" : "enjoy the mongodb articles on phptpoint",
	"tags" : [
		"mongodb",
		"phptpoint"
	]
}
>

The same query can also be written as −

>db.posts.find({post_text:/phptpoint/})

Using regex Expression with Case Insensitive

We use the $options parameter with the $i value to render the search case insensitive. The following command looks for strings, regardless of the smaller or capital case, with the term phptpoint.

>db.posts.find({post_text:{$regex:"phptpoint",$options:"$i"}})

The following document, which in various cases contains the word phptpoint, is one of the results returned from this query.

{
   "_id" : ObjectId("53493d37d852429c10000004"),
   "post_text" : "hey! this is my post on phptpoint", 
   "tags" : [ "phptpoint" ]
} 

Using regex for Array Elements

The definition of regex can also be used on the array field. This is especially important when we incorporate the functionality of tags. So, if you want to search for all posts that have tags beginning with the word tutorial (either tutorial or tutorial or tutorial), you can use the following code:

>db.posts.find({tags:{$regex:"tutorial"}})

Optimizing Regular Expression Queries

  • If the fields of the document are indexed, the query uses indexed values to fit the regular expression. In comparison to the regular expression that searches the entire collection, this makes the search very easy.
  • If the standard expression is a prefix expression, all matches are intended to begin with some characters of a string. For example, if the regex expression is ^tut, then only those strings which start with tut must be checked for by the query.

No Sidebar ads