English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MongoDB Regular Expression

Regular expressions are frequently used in all languages to search for patterns or words in any string. MongoDB also uses the $regex operator to provide regular expression functionality for string pattern matching. MongoDB uses PCRE (Perl Compatible Regular Expressions) as the regular expression language.

Differences from text search, we do not need any configuration or command to use regular expressions.

Assuming we have already created a database named posts A document was inserted into the database as follows

> db.posts.insert(
{
   "post_text": "enjoy the mongodb articles on w3codebox",
   "tags": [
      "mongodb",
      "w3codebox"
   ]
}
WriteResult({ "nInserted": 1 })

Using regular expressions

The following regex query searches for strings containing the string w3All posts of codebox -

> db.posts.find({post_text:{$regex:"w3codebox"}}).pretty(){
	"_id": ObjectId("5dd7ce28f1dd4583e7103fe0"),
	"post_text": "enjoy the mongodb articles on w3codebox",
	"tags": [
		"mongodb",
		"w3codebox"
	]
}
{
	"_id": ObjectId("5dd7d111f1dd4583e7103fe2")
	"post_text": "enjoy the mongodb articles on w3codebox",
	"tags": [
		"mongodb",
		"w3codebox"
	]
}
">

The same query can also be written as-

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

Using a case-insensitive regular expression

To make the search case-insensitive, we use$optionswith value parameters$iThe following command will find strings containing the wordw3codebox, case-insensitive or lowercase letters-

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

One of the results returned by this query is the following document, which includesw3codeboxWords under different situations-

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

Use Regular Expression on Array Elements

We can also use the concept of regular expressions on array fields. This is particularly important when we implement the tag feature. Therefore, if you want to search all words with tags that start with the word tutorial (教程 or tutorialpoint or tutorialphp), you can use the following code-

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

Optimize Regular Expression Query

  • If the document field isindexedThe query will use the index value to match the regular expression. Compared with regular expression scanning the entire collection, this makes the search very fast.

  • If the regular expression isprefix expressionThen all matching items must start with a certain string character. For example, if the regex expression is^tutThen the query must only search those strings that start withtut.