好得很程序员自学网

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

MongoDB 覆盖索引查询

MongoDB 覆盖索引查询

官方的MongoDB的文档中说明,覆盖查询是以下的查询:

所有的查询字段是索引的一部分 所有的查询返回字段在同一个索引中

由于所有出现在查询中的字段是索引的一部分, MongoDB 无需在整个数据文档中检索匹配查询条件和返回使用相同索引的查询结果。

因为索引存在于RAM中,从索引中获取数据比通过扫描文档读取数据要快得多。

使用覆盖索引查询

为了测试覆盖索引查询,使用以下 users 集合:

{
   "_id": ObjectId("53402597d852426020000002"),
   "contact": "987654321",
   "dob": "01-01-1991",
   "gender": "M",
   "name": "Tom Benzamin",
   "user_name": "tombenzamin"
}

我们在 users 集合中创建联合索引,字段为 gender 和 user_name :

>db.users.createIndex({gender:1,user_name:1})

注: 5.0 之前版本可以使用 db.collection.ensureIndex() ,但 ensureIndex() 在 5.0 版本后已被移除,使用 createIndex() 代替。

现在,该索引会覆盖以下查询:

>db.users.find({gender:"M"},{user_name:1,_id:0})

也就是说,对于上述查询,MongoDB的不会去数据库文件中查找。相反,它会从索引中提取数据,这是非常快速的数据查询。

由于我们的索引中不包括 _id 字段,_id在查询中会默认返回,我们可以在MongoDB的查询结果集中排除它。

下面的实例没有排除_id,查询就不会被覆盖:

>db.users.find({gender:"M"},{user_name:1})

最后,如果是以下的查询,不能使用覆盖索引查询:

所有索引字段是一个数组 所有索引字段是一个子文档

查看更多关于MongoDB 覆盖索引查询的详细内容...

  阅读:27次

上一篇

下一篇

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