使用 $regex 运算符进行模式匹配 没有 $regex 运算符的模式匹配
使用 $regex 运算符进行模式匹配
语法格式
{ <field>: { $regex: /pattern/, $options: ‘<options>’ } } 或者 { <field>: { $regex: ‘pattern’ , $options: ‘<options>’ } }
“i”字符用于匹配字符串中的小写和大写模式。 “^”和“$”符号用于在文档中搜索特定模式。“^”符号用来保证字符串以某个字符开始,$用来保证字符串以某个字符结尾。 “x”字符用于忽略字符串中的所有空白字符。
>db.posts.find({post_text:{$regex:"runoon"}})
>db.posts.find({post_text:/runoon/})
不区分大小写的正则表达式
>db.posts.find({post_text:{$regex:"runoon",$options:"$i"}})
{
"_id" : ObjectId("53493d37d852429c10000004"),
"post_text" : "hey! this is my post on runoon",
"tags" : [ "runoon" ]
}
数组元素使用正则表达式
>db.posts.find({tags:{$regex:"run"}})
优化正则表达式查询
如果你的文档中字段设置了索引,那么使用索引相比于正则表达式匹配查找所有的数据查询速度更快。 如果正则表达式是前缀表达式,所有匹配的数据将以指定的前缀字符串为开始。例如:如果正则表达式为 ^tut ,查询语句将查找以 tut 为开头的字符串。
var name=eval("/" + 变量值key +"/i");
title:eval("/"+title+"/i") // 等同于 title:{$regex:title,$Option:"$i"}
长按二维码关注公众号,查阅更多教程