Compound Indexes复合索引

On this page本页内容

MongoDB supports compound indexes, where a single index structure holds references to multiple fields [1] within a collection’s documents.MongoDB支持复合索引,其中单个索引结构包含对集合文档中多个字段[1]的引用。The following diagram illustrates an example of a compound index on two fields:下图显示了两个字段上的复合索引示例:

Diagram of a compound index on the ``userid`` field (ascending) and the ``score`` field (descending). The index sorts first by the ``userid`` field and then by the ``score`` field.
[1]MongoDB imposes a limit of 32 fields for any compound index.MongoDB对任何复合索引设置了32个字段的限制

Compound indexes can support queries that match on multiple fields.复合索引可以支持在多个字段上匹配的查询。

Create a Compound Index创建复合索引

To create a compound index use an operation that resembles the following prototype:要创建复合索引,请使用类似以下原型的操作:

db.collection.createIndex( { <field1>: <type>, <field2>: <type2>, ... } )

The value of the field in the index specification describes the kind of index for that field.索引规范中字段的值描述了该字段的索引类型。For example, a value of 1 specifies an index that orders items in ascending order.例如,值为1指定按升序排列项的索引。A value of -1 specifies an index that orders items in descending order.-1指定按降序排列项目的索引。For additional index types, see index types.有关其他索引类型,请参见索引类型

Important重要

You may not create compound indexes that have hashed index type.不能创建具有hashed索引类型的复合索引。You will receive an error if you attempt to create a compound index that includes a hashed index field.如果尝试创建包含哈希索引字段的复合索引,则会收到一个错误。

Consider a collection named products that holds documents that resemble the following document:考虑一个名为products的集合,它包含类似于以下文档的文档:

{
 "_id": ObjectId(...),
 "item": "Banana",
 "category": ["food", "produce", "grocery"],
 "location": "4th Street Store",
 "stock": 4,
 "type": "cases"
}

The following operation creates an ascending index on the item and stock fields:以下操作在itemstock字段上创建升序索引:

db.products.createIndex( { "item": 1, "stock": 1 } )

The order of the fields listed in a compound index is important.复合索引中列出的字段的顺序很重要。The index will contain references to documents sorted first by the values of the item field and, within each value of the item field, sorted by values of the stock field.索引将包含对文档的引用,这些文档首先按item字段的值排序,在item字段的每个值中,按stock字段的值排序。See Sort Order for more information.有关详细信息,请参见排序顺序

In addition to supporting queries that match on all the index fields, compound indexes can support queries that match on the prefix of the index fields.除了支持匹配所有索引字段的查询外,复合索引还可以支持匹配索引字段前缀的查询。That is, the index supports queries on the item field as well as both item and stock fields:也就是说,索引支持对item字段以及itemstock字段的查询:

db.products.find( { item: "Banana" } )
db.products.find( { item: "Banana", stock: { $gt: 5 } } )

For details, see Prefixes.有关详细信息,请参见前缀

Sort Order排序顺序

Indexes store references to fields in either ascending (1) or descending (-1) sort order.索引以升序(1)或降序(-1)排序顺序存储对字段的引用。For single-field indexes, the sort order of keys doesn’t matter because MongoDB can traverse the index in either direction.对于单字段索引,键的排序顺序无关紧要,因为MongoDB可以在任意方向遍历索引。However, for compound indexes, sort order can matter in determining whether the index can support a sort operation.但是,对于复合索引,排序顺序在确定索引是否支持排序操作时很重要。

Consider a collection events that contains documents with the fields username and date.考虑一个包含usernamedate字段的文档的集合事件。Applications can issue queries that return results sorted first by ascending username values and then by descending (i.e. more recent to last) date values, such as:应用程序可以发出查询,返回先按升序username值排序,然后按降序(即从最近到最后)date值排序的结果,例如:

db.events.find().sort( { username: 1, date: -1 } )

or queries that return results sorted first by descending username values and then by ascending date values, such as:或返回先按username值降序,然后按date值升序排序的结果的查询,例如:

db.events.find().sort( { username: -1, date: 1 } )

The following index can support both these sort operations:以下索引可以支持这两种排序操作:

db.events.createIndex( { "username" : 1, "date" : -1 } )

However, the above index cannot support sorting by ascending username values and then by ascending date values, such as the following:但是,上面的索引不支持先按username值升序,然后date按值升序排序,例如:

db.events.find().sort( { username: 1, date: 1 } )

For more information on sort order and compound indexes, see Use Indexes to Sort Query Results.有关排序顺序和复合索引的详细信息,请参阅使用索引对查询结果排序

Prefixes前缀

Index prefixes are the beginning subsets of indexed fields.索引前缀是索引字段的起始子集。For example, consider the following compound index:例如,考虑以下复合索引:

{ "item": 1, "location": 1, "stock": 1 }

The index has the following index prefixes:索引具有以下索引前缀:

For a compound index, MongoDB can use the index to support queries on the index prefixes.对于复合索引,MongoDB可以使用索引来支持对索引前缀的查询。As such, MongoDB can use the index for queries on the following fields:因此,MongoDB可以使用索引来查询以下字段:

MongoDB can also use the index to support a query on the item and stock fields, since the item field corresponds to a prefix.MongoDB还可以使用索引来支持对itemstock字段的查询,因为item字段对应于前缀。However, in this case the index would not be as efficient in supporting the query as it would be if the index were on only item and stock.但是,在这种情况下,索引在支持查询方面的效率不如索引仅针对itemstock时的效率。Index fields are parsed in order; if a query omits a particular index prefix, it is unable to make use of any index fields that follow that prefix.索引字段按顺序进行分析;如果查询省略了特定的索引前缀,则无法使用该前缀后面的任何索引字段。

Since a query on item and stock omits the location index prefix, it cannot use the stock index field which follows location.由于对itemstock的查询省略了location索引前缀,因此不能使用location后面的stock索引字段。Only the item field in the index can support this query.只有索引中的item字段才能支持此查询。See Create Indexes to Support Your Queries for more information.有关详细信息,请参见创建索引以支持查询

MongoDB cannot use the index to support queries that include the following fields since without the item field, none of the listed fields correspond to a prefix index:MongoDB不能使用索引来支持包含以下字段的查询,因为如果没有item字段,则列出的字段都不对应于前缀索引:

If you have a collection that has both a compound index and an index on its prefix (e.g. { a: 1, b: 1 } and { a: 1 }), if neither index has a sparse or unique constraint, then you can remove the index on the prefix (e.g. { a: 1 }).如果集合的前缀既有复合索引又有索引(例如{a:1, b:1}{a:1}),如果索引都不是稀疏约束或唯一约束,则可以删除前缀上的索引(例如{a:1})。MongoDB will use the compound index in all of the situations that it would have used the prefix index.MongoDB将在所有使用前缀索引的情况下使用复合索引。

Index Intersection索引交集

Starting in version 2.6, MongoDB can use index intersection to fulfill queries.从版本2.6开始,MongoDB可以使用索引交集来完成查询。The choice between creating compound indexes that support your queries or relying on index intersection depends on the specifics of your system.创建支持查询的复合索引还是依赖索引交集取决于系统的具体情况。See Index Intersection and Compound Indexes for more details.有关详细信息,请参见索引交集和复合索引

Additional Considerations其他注意事项

Applications may encounter reduced performance during index builds, including limited read/write access to the collection.应用程序在索引生成期间可能会遇到性能降低的问题,包括对集合的读/写访问受限。For more information on the index build process, see Index Builds on Populated Collections, including the Index Builds in Replicated Environments section.有关索引生成过程的更多信息,请参阅在已填充集合上的索引生成,包括副本环境中的索引生成部分。

Some drivers may specify indexes, using NumberLong(1) rather than 1 as the specification.一些驱动程序可能指定索引,使用NumberLong(1)而不是1作为规范。This does not have any affect on the resulting index.这对结果索引没有任何影响。