WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

MongoDB - Regular Expression


MongoDB also provides functionality of regular expression for string pattern matching using the $regex operator.

MongoDB uses Perl Compatible Regular Expression as regular expression language.
{
   "post_text": "enjoy the mongodb articles on welookups",
   "tags": [
      "mongodb",
      "welookups"
   ]
}

Using regex Expression

The following regex query searches for all the posts containing string welookups in it
>db.posts.find({post_text:{$regex:"welookups"}})
The same query can also be written as
>db.posts.find({post_text:/welookups/})

Using regex Expression with Case Insensitive

we use the $options parameter with value $i. The following command will look for strings having the word welookups, irrespective of smaller or capital case
>db.posts.find({post_text:{$regex:"welookups",$options:"$i"}})
One of the results returned from this query is the following document which contains the word welookups in different cases
{
   "_id" : ObjectId("53493d37d852429c10000004"),
   "post_text" : "hey! this is my post on welookups", 
   "tags" : [ "welookups" ]
} 
 

Using regex for Array Elements

We can also use the concept of regex on array field. This is particularly very important when we implement the functionality of tags. So, if you want to search for all the posts having tags beginning from the word tutorial (either welookups tutorial ), you can use the following code

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





Welookups is optimized for learning.Copy right 2018 kumar aditya singh .
All Right Reserved and you agree to have read and accepted our term and condition.
All Rights Reserved.