MongoDB Regular Expressions
A regular expression is a single string used to describe and match a series of strings that conform to a certain syntactic rule.
Many programming languages support string operations using regular expressions.
MongoDB uses the$regexoperator to set the regular expression for matching strings.
MongoDB uses PCRE (Perl Compatible Regular Expression) as its regular expression language.
Unlike full-text search, using regular expressions requires no configuration.
Consider the followingpostsdocument structure of the collection, which contains the article content and tags:
{
"post_text": "enjoy the mongodb articles on example",
"tags": [
"mongodb",
"example"
]
}
Using Regular Expressions
The following command uses a regular expression to find articles containing the string example:
>db.posts.find({post_text:{$regex:"example"}})
The above query can also be written as:
>db.posts.find({post_text:/example/})
Case-Insensitive Regular Expressions
If the search needs to be case-insensitive, we can set $options to $i.
The following command will find the case-insensitive string example:
>db.posts.find({post_text:{$regex:"example",$options:"$i"}})
The collection will return all data containing the string example, case-insensitively:
{
"_id" : ObjectId("53493d37d852429c10000004"),
"post_text" : "hey! this is my post on example",
"tags" : [ "example" ]
}
Using Regular Expressions on Array Elements
We can also use regular expressions in array fields to search for content. This is very useful in the implementation of tags. If you need to find tag data starting with run (ru or run or example), you can use the following code:
>db.posts.find({tags:{$regex:"run"}})
Optimizing Regular Expression Queries
- If an index is set on a field in your documents, using the index is faster than using a regular expression to match and find all the data.
- If the regular expression is a prefix expression, all matched data will begin with the specified prefix string. For example: If the regular expression is ^tut , the query will look for strings that start with tut.
There are two points to note when using regular expressions here:
Using variables in regular expressions. Be sure to use eval to convert the concatenated string; you cannot directly pass the concatenated string to the expression. Otherwise, there is no error message, just an empty result! Example below:
var name=eval("/" + 变量值key +"/i");
The following is a fuzzy query that contains the title keyword and is case-insensitive:
title:eval("/"+title+"/i") // 等同于 title:{$regex:title,$Option:"$i"}
Other Extensions