MongoDB regular expressions
Regular expressions use a single string to describe and match a series of strings that conform to a certain syntax rule.
Many programming languages support string operations using regular expressions.
MongoDB uses the $regex operator to set a regular expression that matches a string.
MongoDB uses PCRE (Perl Compatible Regular Expression) as the regular expression language.
Unlike full-text search, we don’t need to do any configuration when using 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" ] }
Use regular expressions
The following The command uses regular expressions to find articles containing the w3cschool.cc string:
>db.posts.find({post_text:{$regex:"w3cschool.cc"}})
The above query can also be written as:
>db.posts.find({post_text:/w3cschool.cc/})
Case-insensitive regular expression
If the search needs to be case-insensitive, we can set $options to $i.
The following command will find the case-insensitive string w3cschool.cc:
>db.posts.find({post_text:{$regex:"w3cschool.cc",$options:"$i"}})
All data containing the string w3cschool.cc will be returned in the collection and will not be case-sensitive:
{ "_id" : ObjectId("53493d37d852429c10000004"), "post_text" : "hey! this is my post on W3Cschool.cc", "tags" : [ "tutorialspoint" ] }
Using regular expressions for array elements
We can also use regular expressions to find content in array fields. This is very useful in tag implementation, if you need to find tag data that starts with tutorial (tutorial or tutorials or tutorialpoint or tutorialphp), You can use the following code:
>db.posts.find({tags:{$regex:"tutorial"}})
Optimize regular expression query
If the fields in your document are indexed, then using the index is better than regular expression Expression matching searches all data for faster queries.
If the regular expression is a prefix expression, all matching data will start with the specified prefix string. For example: If the regular expression is ^tut , the query statement will find the string starting with tut.
There are two points to note when using regular expressions:
Use variables in regular expressions. You must use eval to convert the combined string. You cannot directly concatenate the string and pass it into the expression. Otherwise, no error message is reported, but the result is empty! Examples are as follows:
var name=eval("/" + 变量值key +"/i");
The following is a fuzzy query that contains the title keyword and is not case-sensitive:
title:eval("/"+title+"/i") // 等同于 title:{$regex:title,$Option:"$i"}