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 $regex operator 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 following posts collection's document structure, which contains article content and tags:
{
"post_text": "enjoy the mongodb articles on runoob",
"tags": [
"mongodb",
"runoob"
]
}
Using regular expressions
The following command uses a regular expression to find articles containing the string runoob:
>db.posts.find({post_text:{$regex:"runoob"}})
The above query can also be written as:
>db.posts.find({post_text:/runoob/})
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 runoob:
>db.posts.find({post_text:{$regex:"runoob",$options:"$i"}})
The collection will return all data containing the string runoob, case-insensitively:
{
"_id" : ObjectId("53493d37d852429c10000004"),
"post_text" : "hey! this is my post on runoob",
"tags" : [ "runoob" ]
}
Using regular expressions on array elements
We can also use regular expressions in array fields to find content. This is very useful for implementing tags. If you need to find tag data containing tags starting with run (ru or run or runoob), you can use the following code:
>db.posts.find({tags:{$regex:"run"}})
Optimizing regular expression queries
- If fields in your documents have indexes, using the index is faster than using regular expression matching to find all the data.
- If the regular expression is a prefix expression, all matching data will begin with the specified prefix string. For example: if the regular expression is ** ^tut **, the query statement will find strings starting with tut.
There are two things to note when using regular expressions here:
Using variables in regular expressions. You must use eval to convert the combined string; you cannot directly pass the concatenated string to the expression. Otherwise, there will be no error message, only an empty result! The example is as follows:
var name=eval("/" + 变量值key +"/i");
The following is a fuzzy query containing the title keyword, case-insensitive:
title:eval("/"+title+"/i") // 等同于 title:{$regex:title,$Option:"$i"}