MongoDB正则表达式

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

与文本搜索不同,不需要使用任何配置或命令来使用正则表达式。

请考虑以下文档结构,其中包含post文本及其标签 -

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

使用正则表达式

以下regex查询搜索包含”zaixian“字符串的所有帖子 -

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

上面的查询也可以写成 -

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

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

要使搜索不区分大小写,可指定$options参数的值为$i。 以下命令将寻找具有单词zaixian的字符串,不管其是小写还是大写字母 -

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

此查询返回的结果之一是以下文档,其中包含大小写字母的”zaixian“单词 -

{
   "_id" : ObjectId("595b99e1f6a6243715b3c316"),
   "post_text" : "hey! this is my post on zaixian zaixian", 
   "tags" : [ "zaixian" ]
},
{
   "_id" : ObjectId("595b99e1f6a6243715b3c317"),
   "post_text" : "hey! this is my post on zaixian zaixian", 
   "tags" : [ "zaixian" ]
}

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

我们也可以在数组字段上使用正则表达式。当实现标签的功能时,这尤其重要。 所以,如果要从单词:tutorial(tutorialtutorials , tutorialpointtutorialphptutorialpythontutorialphp)开始搜索所有具有标签的帖子,可以使用以下代码 -

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

优化正则表达式查询

  • 如果文档字段创建了索引,则查询将使用索引值来匹配正则表达式。 与正常表达式扫描整个集合相比,使用索引值使得搜索非常快。

  • 如果正则表达式是前缀表达式,则所有匹配都是以某个字符串字符开始。 例如,如果正则表达式是^tut,则查询必须仅搜索以tut开头的那些字符串。


上一篇: MongoDB文本搜索 下一篇: MongoDB GridFS