May 17, 2021 MongoDB
A regular expression is a string that uses a single string to describe and match a series of strings that conform to a synth rule.
Many programming languages support stringing with regular expressions.
MongoDB uses $regex operator to set regular expressions that match strings.
MongoDB uses Perl Compatible Regular Expression as the regular expression language.
Unlike full-text retrieval, we don't need to do any configuration with regular expressions.
Consider the document structure of the following posts collection, which contains article content and tags:
{ "post_text": "enjoy the mongodb articles on tutorialspoint", "tags": [ "mongodb", "tutorialspoint" ] }
The following command uses regular expressions to find articles that contain w3cschool.cn string:
>db.posts.find({post_text:{$regex:"w3cschool.cn"}})
The above query can also be written as:
>db.posts.find({post_text:/w3cschool.cn/})
If the retrieval needs to be case insensosens $options set $i.
The following command looks for case-insens w3cschool.cn:
>db.posts.find({post_text:{$regex:"w3cschool.cn",$options:"$i"}})
All data containing the string w3cschool.cn is returned in the collection and is case insenso sensitive:
{ "_id" : ObjectId("53493d37d852429c10000004"), "post_text" : "hey! this is my post on W3Cschool.cc", "tags" : [ "tutorialspoint" ] }
We can also use regular expressions in array fields to find content. This is useful in the implementation of tags, and if you need to find tag data that starts with tutorials ( tutorials or tutorials or tutorialpoints or tutorialphp), you can use the following code:
>db.posts.find({tags:{$regex:"tutorial"}})