好得很程序员自学网

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

MongoDB 高级索引

MongoDB 高级索引

考虑以下文档集合(users ):

{
   "address": {
      "city": "Los Angeles",
      "state": "California",
      "pincode": "123"
   },
   "tags": [
      "music",
      "cricket",
      "blogs"
   ],
   "name": "Tom Benzamin"
}

以上文档包含了 address 子文档和 tags 数组。

索引数组字段

假设我们基于标签来检索用户,为此我们需要对集合中的数组 tags 建立索引。

在数组中创建索引,需要对数组中的每个字段依次建立索引。所以在我们为数组 tags 创建索引时,会为 music、cricket、blogs三个值建立单独的索引。

使用以下命令创建数组索引:

>db.users.ensureIndex({"tags":1})

创建索引后,我们可以这样检索集合的 tags 字段:

>db.users.find({tags:"cricket"})

为了验证我们使用使用了索引,可以使用 explain 命令:

>db.users.find({tags:"cricket"}).explain()

以上命令执行结果中会显示 "cursor" : "BtreeCursor tags_1" ,则表示已经使用了索引。

索引子文档字段

假设我们需要通过city、state、pincode字段来检索文档,由于这些字段是子文档的字段,所以我们需要对子文档建立索引。

为子文档的三个字段创建索引,命令如下:

>db.users.ensureIndex({"address.city":1,"address.state":1,"address.pincode":1})

一旦创建索引,我们可以使用子文档的字段来检索数据:

>db.users.find({"address.city":"Los Angeles"})   

查询表达不一定遵循指定的索引的顺序,mongodb 会自动优化。所以上面创建的索引将支持以下查询:

>db.users.find({"address.state":"California","address.city":"Los Angeles"}) 

同样支持以下查询:

>db.users.find({"address.city":"Los Angeles","address.state":"California","address.pincode":"123"})

查看更多关于MongoDB 高级索引的详细内容...

  阅读:25次

上一篇

下一篇

第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 正则表达式