问题
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