A regular expression uses a single string to describe and match a series of strings that conform to a syntactic rule.
Many programming languages support string manipulation using regular expressions.
MongoDB usage $regex Operator to set the regular expression that matches the string.
MongoDB uses PCRE (Perl Compatible Regular Expression) as the regular expression language.
Unlike full-text retrieval, we don’t need to do any configuration to use regular expressions.
Consider the following posts The document structure of the collection that contains the article content and tags:
{
"post_text": "enjoy the mongodb articles on runoob",
"tags": [
"mongodb",
"runoob"
]
}
3.41.1. Use regular expressions ¶
The following command uses regular expressions to find articles that contain runoob strings:
>db.posts.find({post_text:{$regex:"runoob"}})
The above query can also be written as:
>db.posts.find({post_text:/runoob/})
3.41.2. Case-insensitive regular expression ¶
If retrieval needs to be case-insensitive, we can set $options to $I.
The following command looks for the case-insensitive string runoob:
>db.posts.find({post_text:{$regex:"runoob",$options:"$i"}})
All data containing the string runoob is returned in the collection, and is case-insensitive:
{
"_id" : ObjectId("53493d37d852429c10000004"),
"post_text" : "hey! this is my post on runoob",
"tags" : [ "runoob" ]
}
3.41.3. Array elements use regular expressions ¶
We can also use regular expressions in array fields to find content. This is very useful for tag implementation. If you need to find tag data that starts with run (ru or run or runoob), you can use the following code:
>db.posts.find({tags:{$regex:"run"}})
3.41.4. Optimize regular expression query ¶
If the fields in your document are indexed, then using the index to find all the data queries is faster than regular expression matching.
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 will look for a string that begins with tut.
There are two points to note when using regular expressions:
Variables are used in regular expressions. Be sure to use eval to convert the combined string, and you can’t pass the string into the expression directly after concatenation. Otherwise, there is no wrong information, but the result is empty! Examples are as follows:
var name=eval("/" + 变量值key +"/i");
The following is a fuzzy query that contains title keywords and is not case-sensitive:
title:eval("/"+title+"/i") // 等同于 title:{$regex:title,$Option:"$i"}