Mongodb Regular Expression
# MongoDB Regular Expressions
A regular expression is a special string that describes a search pattern. You can think of regular expressions as a specialized programming language for searching and manipulating text.
Many programming languages support string operations using regular expressions.
MongoDB uses the **$regex** operator to set regular expressions for matching strings.
MongoDB uses PCRE (Perl Compatible Regular Expressions) as its regular expression language.
Unlike full-text search, using regular expressions does not require any configuration.
Consider the following document structure in the **posts** collection, which contains article content and tags:
{ "post_text": "enjoy the mongodb articles on tutorial", "tags": [ "mongodb", "tutorial" ]}
* * *
## Using Regular Expressions
The following command uses a regular expression to find articles containing the string "tutorial":
>db.posts.find({post_text:{$regex:"tutorial"}})
The above query can also be written as:
>db.posts.find({post_text:/tutorial/})
* * *
## Case-Insensitive Regular Expressions
If the search needs to be case-insensitive, we can set the $options to $i.
The following command will find the string "tutorial" case-insensitively:
>db.posts.find({post_text:{$regex:"tutorial",$options:"$i"}})
The collection will return all data containing the string "tutorial", case-insensitively:
{ "_id" : ObjectId("53493d37d852429c10000004"), "post_text" : "hey! this is my post on tutorial", "tags" : }
* * *
## Using Regular Expressions on Array Elements
We can also use regular expressions to search for content within array fields. This is very useful for tag implementations. If you need to find data with tags starting with "run" (like "ru", "run", or "tutorial"), you can use the following code:
>db.posts.find({tags:{$regex:"run"}})
* * *
## Optimizing Regular Expression Queries
* If you have an index set on a field in your document, 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 matching data will start with the specified prefix string. For example: if the regular expression is **^tut**, the query will look for strings starting with "tut".
**There are two points to note when using regular expressions here:**
Using variables in regular expressions. You must use `eval` to convert the combined string; you cannot directly concatenate the string and pass it to the expression. Otherwise, there will be no error message, but the result will be empty! Example:
var name=eval("/" + variableKey +"/i");
The following is a fuzzy query containing the keyword "title", case-insensitive:
title:eval("/"+title+"/i") // Equivalent to title:{$regex:title,$Option:"$i"}
YouTip