Regular Expression in MongoDB

Regular Expression is used frequently in all languages ​​to search for a pattern or a word in any string. MongoDB also provides Regular Expression to match Pattern matching in string by using $ regex operator. MongoDB uses PCRE (Perl Compatible Regular Expression) as the Regular Expression language.

Regular Expression is used frequently in all languages ​​to search for a pattern or a word in any string. MongoDB also provides Regular Expression to match Pattern matching in string by using $ regex operator. MongoDB uses PCRE (Perl Compatible Regular Expression) as the Regular Expression language.

Unlike Text Search, we do not need to execute any command or configuration to use Regular Expression.

You follow the structure of the Document under the posts collection containing the following posts_text and tags fields:

 { "post_text" : "enjoy the mongodb articles on tutorialspoint" , "tags" : [ "mongodb" , "tutorialspoint" ] } 

Use regex in MongoDB

Query the following regex to search all posts that contain the tutorialspoint string in it:

 > db . posts . find ({ post_text :{ $regex : "tutorialspoint" }}) 

The same query can be written as follows:

 > db . posts . find ({ post_text : /tutorialspoint/ }) 

Use regex with options that are not case sensitive

To make the search caseless, use the $ options parameter with the value $ i . The following command will search for strings that have the word tutorialspoint, regardless of whether they are uppercase or lowercase.

 > db . posts . find ({ post_text :{ $regex : "tutorialspoint" , $options : "$i" }}) 

One of the results of this query is the following Document which contains the word tutorialspoint in different typefaces:

 { "_id" : ObjectId ( "53493d37d852429c10000004" ), "post_text" : "hey! this is my post on TutorialsPoint" , "tags" : [ "tutorialspoint" ] } 

Use regex for array elements

We can also use the term regex on the array field. This is especially important when we implement the features of tags. Therefore, if you want to search all posts with tags starting with the tutorial word, you can use the following code:

 > db . posts . find ({ tags :{ $regex : "tutorial" }}) 

Optimize queries for Regular Expression

If the Document fields are already indexed , the query will use these indexed values ​​to match the Regular Expressions. This makes searching faster when compared to scanning the entire Collection.

If Regular Expression is a Prefix expression, all matches are started with a specific string. For example, if the regex is ^ tut, the query will only find strings that start with the tut.

According to Tutorialspoint

Previous post: Text Search in MongoDB

Next article: Working with Rockmongo

4.3 ★ | 4 Vote