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重要

Starting in MongoDB 4.4:从MongoDB 4.4开始:

In MongoDB 4.2 or earlier:

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字段的文档的events集合。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:索引具有以下索引前缀:

  • { item: 1 }
  • { item: 1, location: 1 }

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可以使用索引查询以下字段:

  • the item field,item字段
  • the item field and the location field,item字段和location字段,
  • the item field and the location field and the stock field.item字段、location字段和stock字段

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字段,列出的字段中没有一个对应于前缀索引:

  • the location field,location字段
  • the stock field, orstock字段,或
  • the location and stock fields.location字段和stock字段

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.这对结果索引没有任何影响。

←  Single Field IndexesMultikey Indexes →