好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

MongoDB 正则表达式

MongoDB 正则表达式

正则表达式是使用单个字符串来描述、匹配一系列符合某个句法规则的字符串。

许多程序设计语言都支持利用正则表达式进行字符串操作。

MongoDB 使用 $regex 操作符来设置匹配字符串的正则表达式。

MongoDB使用PCRE (Perl Compatible Regular Expression) 作为正则表达式语言。

不同于全文检索,我们使用正则表达式不需要做任何配置。

考虑以下 posts 集合的文档结构,该文档包含了文章内容和标签:

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

使用正则表达式

以下命令使用正则表达式查找包含 hdhcms 字符串的文章:

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

以上查询也可以写为:

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

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

如果检索需要不区分大小写,我们可以设置 $options 为 $i。

以下命令将查找不区分大小写的字符串 hdhcms:

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

集合中会返回所有包含字符串 hdhcms 的数据,且不区分大小写:

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

数组元素使用正则表达式

我们还可以在数组字段中使用正则表达式来查找内容。 这在标签的实现上非常有用,如果你需要查找包含以 run 开头的标签数据(ru 或 run 或 hdhcms), 你可以使用以下代码:

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

优化正则表达式查询

如果你的文档中字段设置了索引,那么使用索引相比于正则表达式匹配查找所有的数据查询速度更快。

如果正则表达式是前缀表达式,所有匹配的数据将以指定的前缀字符串为开始。例如: 如果正则表达式为 ^tut ,查询语句将查找以 tut 为开头的字符串。

这里面使用正则表达式有两点需要注意:

正则表达式中使用变量。一定要使用eval将组合的字符串进行转换,不能直接将字符串拼接后传入给表达式。否则没有报错信息,只是结果为空!实例如下:

var name=eval("/" + 变量值key +"/i"); 

以下是模糊查询包含title关键词, 且不区分大小写:

title:eval("/"+title+"/i")    // 等同于 title:{$regex:title,$Option:"$i"}   

查看更多关于MongoDB 正则表达式的详细内容...

  阅读:22次

上一篇

下一篇

第1节:Linux 平台安装 MongoDB    第2节:MongoDB $type 操作符    第3节:MongoDB Limit与Skip方法    第4节:MongoDB Map Reduce    第5节:MongoDB ObjectId    第6节:MongoDB GridFS    第7节:MongoDB 插入文档    第8节:MongoDB 查询文档    第9节:MongoDB 分片    第10节:MongoDB 备份(mongodump)与恢复(mongorestore)    第11节:MongoDB PHP    第12节:MongoDB 复制(副本集)    第13节:MongoDB 查询分析    第14节:MongoDB 覆盖索引查询    第15节:MongoDB 简介    第16节:MongoDB 概念解析    第17节:MongoDB 连接    第18节:MongoDB 教程    第19节:MongoDB 更新文档    第20节:MongoDB 聚合    第21节:MongoDB 索引    第22节:MongoDB 排序    第23节:MongoDB 删除文档    第24节:MongoDB 监控    第25节:MongoDB 关系    第26节:MongoDB 数据库引用    第27节:MongoDB 全文检索    第28节:MongoDB 高级索引    第29节:MongoDB 管理工具: Rockmongo    第30节:MongoDB 固定集合(Capped Collections)    第31节:NoSQL 简介    第32节:Windows 平台安装 MongoDB    第33节:MongoDB 条件操作符    第34节:MongoDB 原子操作    第35节:MongoDB 索引限制    第36节:MongoDB 自动增长    第37节:MongoDB 正则表达式