小白教程
所有教程
关于
Search
172.69.58.95
172.69.58.95
参数设置
贡献
退出
操作
编辑
移动
保护
信息
历史
删除
查看“MongoDB 正则表达式”的源代码
本页内容
上一节:
MongoDB_全文检索
下一节:
MongoDB_管理工具:_Rockmongo
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
{{DISPLAYTITLE:MongoDB 正则表达式}}[[Category:MongoDB 教程|42]] = MongoDB 正则表达式 = 正则表达式是使用单个字符串来描述、匹配一系列符合某个句法规则的字符串。 许多程序设计语言都支持利用正则表达式进行字符串操作。 MongoDB 使用 '''$regex''' 操作符来设置匹配字符串的正则表达式。 MongoDB使用PCRE (Perl Compatible Regular Expression) 作为正则表达式语言。 不同于全文检索,我们使用正则表达式不需要做任何配置。 考虑以下 '''posts''' 集合的文档结构,该文档包含了文章内容和标签: <sample title="" desc="" lang="mongodb" hererun="1"> { "post_text": "enjoy the mongodb articles on xiaobai", "tags": [ "mongodb", "xiaobai" ] } </sample> == 使用正则表达式 == 以下命令使用正则表达式查找包含 xiaobai 字符串的文章: <sample title="" desc="" lang="mongodb" hererun="1"> >db.posts.find({post_text:{$regex:"xiaobai"}}) </sample> 以上查询也可以写为: <sample title="" desc="" lang="mongodb" hererun="1"> >db.posts.find({post_text:/xiaobai/}) </sample> == 不区分大小写的正则表达式 == 如果检索需要不区分大小写,我们可以设置 $options 为 $i。 以下命令将查找不区分大小写的字符串 xiaobai: <sample title="" desc="" lang="mongodb" hererun="1"> >db.posts.find({post_text:{$regex:"xiaobai",$options:"$i"}}) </sample> 集合中会返回所有包含字符串 xiaobai 的数据,且不区分大小写: <sample title="" desc="" lang="mongodb" hererun="1"> { "_id" : ObjectId("53493d37d852429c10000004"), "post_text" : "hey! this is my post on xiaobai", "tags" : [ "xiaobai" ] } </sample> == 数组元素使用正则表达式 == 我们还可以在数组字段中使用正则表达式来查找内容。 这在标签的实现上非常有用,如果你需要查找包含以 run 开头的标签数据(ru 或 run 或 xiaobai), 你可以使用以下代码: <sample title="" desc="" lang="mongodb" hererun="1"> >db.posts.find({tags:{$regex:"run"}}) </sample> == 优化正则表达式查询 == * 如果你的文档中字段设置了索引,那么使用索引相比于正则表达式匹配查找所有的数据查询速度更快。 * 如果正则表达式是前缀表达式,所有匹配的数据将以指定的前缀字符串为开始。例如: 如果正则表达式为 '''^tut''' ,查询语句将查找以 tut 为开头的字符串。 '''这里面使用正则表达式有两点需要注意:''' 正则表达式中使用变量。一定要使用eval将组合的字符串进行转换,不能直接将字符串拼接后传入给表达式。否则没有报错信息,只是结果为空!实例如下: <sample title="" desc="" lang="mongodb" hererun="1"> var name=eval("/" + 变量值key +"/i"); </sample> 以下是模糊查询包含title关键词, 且不区分大小写: <sample title="" desc="" lang="mongodb" hererun="1"> title:eval("/"+title+"/i") // 等同于 title:{$regex:title,$Option:"$i"} </sample>
返回至“
MongoDB 正则表达式
”。
上一节:
MongoDB_全文检索
下一节:
MongoDB_管理工具:_Rockmongo