问题描述
例如,您可以对两个字段执行MongoDB涵盖的查询吗?
Can you perform a MongoDB covered query for two fields, for example
db.collection.find( { _id: 1, a: 2 } )
没有具有复合索引,例如
db.collection.ensureIndex( { _id: 1, a: 1 } )
,但是只为_id提供一个索引(默认情况下为该索引),为字段"a"提供另一个索引,如
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.
推荐答案
查询仅使用一个 index .
您的示例将_id
显示为索引的元素之一? _id
在集合中需要唯一,因此使_id
和其他内容的复合索引没有意义.
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.
如果您改为:
db.collection.ensureIndex( { a: 1, b: 1 })
然后,您可以根据需要独立地使用a
索引,或与b
一起使用复合索引.
You could then use the a
index as needed, independently, or as a compound index with b
.
这篇关于MongoDB涵盖了没有复合索引的两个字段的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!