MongoDB Covered Query For Two Fields Without Compound Index

别等时光非礼了梦想. 提交于 2019-12-11 11:46:16

问题


Can you perform a MongoDB covered query for two fields, for example

db.collection.find( { _id: 1, a: 2 } )

without having a compound index such as

db.collection.ensureIndex( { _id: 1, a: 1 } )

but instead having only one index for _id (you get that by default) and another index for field "a", as in

db.collection.ensureIndex( { a: 1 } )

In other words, I'd like to know if in order to perform a covered query for two fields I need a compound index vs. needing only two single (i.e., not compound) indexes, one for each field.


回答1:


Queries only use one index.

Your example shows _id as one of the elements of your index? _id Needs to be unique in a collection, so it wouldn't make sense to make a compound index of _id and something else.

If you instead had:

db.collection.ensureIndex( { a: 1, b: 1 })

You could then use the a index as needed, independently, or as a compound index with b.



来源:https://stackoverflow.com/questions/14296854/mongodb-covered-query-for-two-fields-without-compound-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!