MongoDB 正则表达式

正则表达式在所有语言中都经常用于搜索任何字符串中的模式或单词。MongoDB 还使用 $regex 运算符为字符串模式匹配提供了正则表达式的功能。MongoDB 使用 PCRE (Perl 兼容正则表达式)作为正则表达式语言。

与文本搜索不同,我们不需要进行任何配置或命令即可使用正则表达式。

假设我们已经在名为 posts 的数据库中插入了一个文档,如下所示

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

使用正则表达式

下面的regex查询搜索包含字符串 nhooo 的所有帖子–

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

相同的查询也可以写成-

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

使用不区分大小写的正则表达式

为了使搜索不区分大小写,我们使用$options带有value的参数$i。以下命令将查找带有单词的字符串nhooo,而不考虑大小写或小写字母-

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

该查询返回的结果之一是以下文档,其中包含nhooo在不同情况下的单词-

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

对数组元素使用正则表达式

我们还可以在数组字段上使用正则表达式的概念。当我们实现标签的功能时,这尤其重要。因此,如果您要搜索所有带有标签的单词,它们都以单词tutorial(教程或tutorialpoint或tutorialphp)开头,则可以使用以下代码-

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

优化正则表达式查询

  • 如果document字段为indexed,则查询将使用索引值来匹配正则表达式。与正则表达式扫描整个集合相比,这使搜索非常快。

  • 如果正则表达式为prefix expression,则所有匹配项均应以某个字符串字符开头。例如,如果regex表达式为^tut,则查询必须仅搜索以开头的那些字符串tut