MongoDB 正则表达式
MongoDB 正则表达式
正则表达式在所有语言中经常用于搜索任何字符串中的模式。MongoDB可以使用$regex运算符为字符串模式匹配提供正则表达式功能。MongoDB使用PCRE(Perl兼容正则表达式)作为正则表达式语言。
与文本搜索不同,我们不需要执行任何配置或命令来使用正则表达式。
假设posts集合下以下文档结构:
{ "post_text": "enjoy the mongodb articles on tutorialspoint", "tags": [ "mongodb", "tutorialspoint" ] }
使用正则表达式
下面的regex查询搜索其中包含字符串tutorialspoint的所有帖子-
>db.posts.find({post_text:{$regex:"tutorialspoint"}})
同样的查询也可以写成
>db.posts.find({post_text:/tutorialspoint/})
使用不区分大小写的正则表达式
为了使搜索不区分大小写,我们使用值为$i的$options参数
>db.posts.find({post_text:{$regex:"tutorialspoint",$options:"$i"}})
此查询返回的结果之一是以下文档,其中包含不同情况下的单词tutorialspoint -
{ "_id" : ObjectId("53493d37d852429c10000004"), "post_text" : "hey! this is my post on TutorialsPoint", "tags" : [ "tutorialspoint" ] }
对数组元素使用正则表达式
我们还可以在数组字段上使用正则表达式的概念。当我们实现标签的功能时,这一点尤其重要。因此,如果要搜索所有具有从word教程开始的标记的帖子(教程或教程,或者tutorialpoint或tutorialphp ),可以使用以下代码
>db.posts.find({tags:{$regex:"tutorial"}})
优化正则表达式查询
如果对文档字段进行了索引,则查询将使用索引值来匹配正则表达式。与扫描整个集合的正则表达式相比,这使得搜索非常快。
如果正则表达式是前缀表达式,则所有匹配项都以某个字符串字符开头。例如,如果正则表达式是tut,则查询必须仅搜索以tut开头的那些字符串。