Home >>MongoDB Tutorial >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 })
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/})
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" ] }
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"}})