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。