Regular Expressions are frequently utilized in all languages to search for a sample or word in any string. MongoDB additionally gives functionality of everyday expression for string sample matching using the $regex operator. MongoDB makes use of PCRE (Perl Compatible Regular Expression) as everyday expression language.
Unlike text search, we do now not need to do any configuration or command to apply everyday expressions.
Assume we've inserted a report in a database named posts as shown below −
> db.posts.insert(
{
"post_text": "enjoy the mongodb articles on tutorialspoint",
"tags": [
"mongodb",
"tutorialspoint"
]
}
WriteResult({ "nInserted" : 1 })
Using regex Expression
The following regex query searches for all the posts containing string tutorialspoint in it −
> db.posts.find({post_text:{$regex:"tutorialspoint"}}).pretty()
{
"_id" : ObjectId("5dd7ce28f1dd4583e7103fe0"),
"post_text" : "enjoy the mongodb articles on tutorialspoint",
"tags" : [
"mongodb",
"tutorialspoint"
]
}
{
"_id" : ObjectId("5dd7d111f1dd4583e7103fe2"),
"post_text" : "enjoy the mongodb articles on tutorialspoint",
"tags" : [
"mongodb",
"tutorialspoint"
]
}
>
The identical query also can be written as −
>db.posts.find({post_text:/tutorialspoint/})
Using regex Expression with Case Insensitive
To make the search case insensitive, we use the $alternatives parameter with price $i. The following command will search for strings having the word tutorialspoint, irrespective of smaller or capital case −
>db.posts.find({post_text:{$regex:"tutorialspoint",$options:"$i"}})
One of the results back from this question is the subsequent record which contains the phrase tutorialspoint in special instances −
{
"_id" : ObjectId("53493d37d852429c10000004"),
"post_text" : "hey! this is my post on TutorialsPoint",
"tags" : [ "tutorialspoint" ]
}
Using regex for Array Elements
We also can use the concept of regex on array subject. This is specially very essential whilst we implement the capability of tags. So, if you need to look for all of the posts having tags beginning from the word educational (both educational or tutorials or tutorialpoint or tutorialphp), you can use the subsequent code −
>db.posts.find({tags:{$regex:"tutorial"}})
Optimizing Regular Expression Queries
- If the file fields are indexed, the query will use make use of indexed values to fit the ordinary expression. This makes the search very fast in comparison to the everyday expression scanning the complete series.
- If the everyday expression is a prefix expression, all of the matches are intended to begin with a certain string characters. For e.G., if the regex expression is ^tut, then the question has to look for most effective the ones strings that start with tut.