Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

MongoDB regular expression


May 17, 2021 MongoDB


Table of contents


MongoDB regular expression

A regular expression is a string that uses a single string to describe and match a series of strings that conform to a synth rule.

Many programming languages support stringing with regular expressions.

MongoDB uses $regex operator to set regular expressions that match strings.

MongoDB uses Perl Compatible Regular Expression as the regular expression language.

Unlike full-text retrieval, we don't need to do any configuration with regular expressions.

Consider the document structure of the following posts collection, which contains article content and tags:

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

Use regular expressions

The following command uses regular expressions to find articles that contain w3cschool.cn string:

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

The above query can also be written as:

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

Case-insensed with regular expressions

If the retrieval needs to be case insensosens $options set $i.

The following command looks for case-insens w3cschool.cn:

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

All data containing the string w3cschool.cn is returned in the collection and is case insenso sensitive:

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

Array elements use regular expressions

We can also use regular expressions in array fields to find content. This is useful in the implementation of tags, and if you need to find tag data that starts with tutorials ( tutorials or tutorials or tutorialpoints or tutorialphp), you can use the following code:

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

Optimize regular expression queries

  • If the fields in your document are indexed, it is faster to use indexes to find all data queries than regular expression matches.

  • If the regular expression is a prefix expression, all matching data starts with the specified prefix string. For example: If the regular expression is stut, the query statement looks for strings that begin with tut.