Latest web development tutorials

MongoDB regex

Regular expressions are used to describe the use of a single string, in line with a series of syntactic rules match string.

Many programming languages ​​support the use of regular expressions for string operations.

MongoDB uses $ regex operator to set the string matching regular expression.

MongoDB uses PCRE (Perl Compatible Regular Expression) as a regular expression language.

Unlike full-text search, we use a regular expression does not need to do any configuration.

Consider the following document structure set of posts, the document contains the content of the article and the label:

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

Using regular expressions

The following commands use regular expressions to find article contains w3cschool.cc strings:

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

The above query can also be written as:

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

Case-insensitive regular expressions

If you need to retrieve a case-insensitive, we can set the $ options as $ i.

The following command will find case-insensitive string w3cschool.cc:

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

The collection will return all of the data containing the string w3cschool.cc is not case sensitive:

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

Array elements using regular expressions

We can also use regular expressions in the array field to find content. This is useful in the realization of the label, if you need to find the label contains data (tutorial or tutorials or tutorialpoint or tutorialphp) tutorial at the beginning, you can use the following code:

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

Optimizing Regular Expressions query

  • If your document index field is set, then the use of the index compared to the regular expression matching to find all data queries faster.

  • If the regular expression is a prefix expression, all matching data will be specified prefix string to start. For example: If the regular expression is ^ tut, tut query will look to the beginning of the string.

There is the use of regular expressions There are two points to note:

Regular expressions using variables. Be sure to use a combination of string eval will convert after can not be directly passed to the string concatenation expression. Otherwise there is no error message, but the result is empty! Examples are as follows:

var name=eval("/" + 变量值key +"/i"); 

The following is a fuzzy query contains title keyword is not case sensitive:

title:eval("/"+title+"/i")    // 等同于 title:{$regex:title,$Option:"$i"}