Mongodb Covered Indexes

MongoDB 1.8+ can return data from the index only when the query only involves keys which are present in the index. Not inspecting the actual documents can speed up responses considerably since the index is compact in size and usually fits in RAM, or is sequentially located on disk.

Mongod will automatically use covered index when it can. But be sure that:
  • you provide list of fields to return, so that it can determine that it can be covered by index
  • you must explicitly exclude the _id field by using {_id: 0} (unless the index includes that)
  • as soon as you insert one array value for one of the index keys, the index will immediately become a multikey index and this disables covered index functionality
  • use Explain to determine if the covered index is used: the indexOnly field should be true
// do a login with a covered index, returning the users roles/groups
> db.users.ensureIndex( { username : 1, password : 1, roles : 1} );
> db.users.save({username: "joe", password: "pass", roles: 2})
> db.users.save({username: "liz", password: "pass2", roles: 4})
> db.users.find({username: "joe"}, {_id: 0, roles: 1})
{ "roles" : 2 }
> db.users.find({username: "joe"}, {_id: 0, roles: 1}).explain()
{
	"cursor" : "BtreeCursor username_1_password_1_roles_1",
...
	"indexOnly" : true,
...
}

Mongodb Covered Indexes 在仅仅查询文档中的索引字段值时使用,可以提高性能。判断一个查询是否使用了Covered Indexes: 1) 提供查询的字段必须是索引字段 2)_id默认包含在返回的Object中,所以需要使用_id: 0将其排除 3)索引字段的值不能是数组 4)使用Explain返回的indexOnly必须为true。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值