Database Manual / Indexes / Types

Compound Indexes复合索引

Compound indexes collect and sort data from multiple field values from each document in a collection. You can use the compound index to query the first field or any prefix fields of the index. The order of fields in a compound index is very important. The B-tree created by a compound index stores the sorted data in the order that the index specifies the fields.复合索引从集合中每个文档的多个字段值中集合数据并对其进行排序。您可以使用复合索引查询索引的第一个字段或任何前缀字段。复合索引中字段的顺序非常重要。由复合索引创建的B树按照索引指定字段的顺序存储排序后的数据。

For example, the following image shows a compound index where documents are first sorted by userid in ascending order (alphabetically). Then, the scores for each userid are sorted in descending order:例如,下图显示了一个复合索引,其中文档首先按userid升序(字母顺序)排序。然后,每个useridscores按降序排列:

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.

To create a compound index, use the following prototype:要创建复合索引,请使用以下原型:

db.<collection>.createIndex( {
<field1>: <sortOrder>,
<field2>: <sortOrder>,
...
<fieldN>: <sortOrder>
} )

You can create and manage compound indexes in the UI for deployments hosted in MongoDB Atlas.您可以在MongoDB Atlas中托管的部署的UI中创建和管理复合索引

Use Cases用例

If your application repeatedly runs a query that contains multiple fields, you can create a compound index to improve performance for that query. For example, a grocery store manager often needs to look up inventory items by name and quantity to determine which items are low stock. 如果应用程序反复运行包含多个字段的查询,您可以创建复合索引来提高该查询的性能。例如,杂货店经理经常需要按名称和数量查找库存物品,以确定哪些物品库存不足。You can create a compound index on both the item and quantity fields to improve query performance.您可以在itemquantity字段上创建复合索引,以提高查询性能。

Get Started开始使用

To create a compound index, see Create a Compound Index.要创建复合索引,请参阅创建复合索引

Details详情

This section describes technical details and limitations for compound indexes.本节描述了复合指数的技术细节和限制。

Field Limit字段限制

A single compound index can contain up to 32 fields.单个复合索引最多可包含32个字段。

Field Order字段顺序

The order of the indexed fields impacts the effectiveness of a compound index. Compound indexes contain references to documents according to the order of the fields in the index. 索引字段的顺序会影响复合索引的有效性。复合索引根据索引中字段的顺序包含对文档的引用。To create efficient compound indexes, follow the ESR (Equality, Sort, Range) guideline.要创建高效的复合索引,请遵循ESR(相等、排序、范围)指南

Sort Order排序顺序

Indexes store references to fields in either ascending (1) or descending (-1) sort order. For compound indexes, sort order can determine whether the index supports a sort operation. For more information, see Compound Index Sort Order.索引以升序(1)或降序(-1)的排序顺序存储对字段的引用。对于复合索引,排序顺序可以确定索引是否支持排序操作。有关更多信息,请参阅复合索引排序顺序

Hashed Index Fields哈希索引字段

Compound indexes may contain a single hashed index field.复合索引可能包含一个哈希索引字段

Index Prefixes索引前缀

Index prefixes are the beginning subsets of indexed fields. Compound indexes support queries on all fields included in the index prefix.索引前缀是索引字段的起始子集。复合索引支持对索引前缀中包含的所有字段进行查询。

For example, consider this compound index:例如,考虑这个复合指数:

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

The index has these index prefixes:该索引具有以下索引前缀:

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

MongoDB can use the compound index to support queries on these field combinations:MongoDB可以使用复合索引来支持对这些字段组合的查询:

  • item
  • item and location
  • item, location, and 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. However, the index is not as efficient as { item: 1, stock: 1 }.MongoDB还可以使用索引来支持对itemstock字段的查询,因为item字段对应于前缀。然而,该指数的效率不如{ item: 1, stock: 1 }

For example, consider a query for "item": "saccharomyces cerevisiae" and "stock": 60. 例如,考虑对"item": "saccharomyces cerevisiae""stock": 60的查询。If the collection contains 10000 documents matching "item": "saccharomyces cerevisiae" and only 100 of those documents matching "stock": 60, the query examines 10000 keys. 如果集合包含10000个与"item": "saccharomyces cerevisiae"匹配的文档,而其中只有100个与"stock": 60匹配,则查询将检查10000个键。In the IXSCAN stage, the query filters those keys by the stock field and only returns 100 results to the next stage.IXSCAN阶段,查询按stock字段筛选这些键,只将100个结果返回给下一阶段。

MongoDB's indexing strategy eliminates any need to arrange exact match fields in a particular order. However, if the query does not specify an equality condition on an index prefix that precedes or overlaps with the sort specification, the operation will not efficiently use the index. MongoDB的索引策略消除了以特定顺序排列精确匹配字段的任何需要。但是,如果查询没有在排序规范之前或与排序规范重叠的索引前缀上指定相等条件,则操作将无法有效地使用索引。For more information, see Sort and Non-prefix Subset of an Index.有关详细信息,请参阅索引的排序和无前缀子集

MongoDB cannot use the compound index to support queries on these field combinations:MongoDB不能使用复合索引来支持对这些字段组合的查询:

  • location
  • stock
  • location and stock

Without the item field, none of the preceding field combinations correspond to a prefix index.如果没有item字段,前面的字段组合都不对应于前缀索引。

Tip

Remove Redundant Indexes删除冗余索引

If you have a collection that has both a compound index and an index on its prefix (for example, { a: 1, b: 1 } and { a: 1 }), if neither index has a sparse or unique constraint, you can remove the index on the prefix ({ a: 1 }). MongoDB uses the compound index in all of the situations that it would have used the prefix index.如果一个集合同时具有复合索引和前缀索引(例如,{ a: 1, b: 1 }{ a: 1 }),如果这两个索引都没有稀疏唯一约束,则可以删除前缀上的索引({ a: 1 })。MongoDB在所有使用前缀索引的情况下都使用复合索引。

Sparse Compound Indexes稀疏复合指数

Compound indexes can contain different types of sparse indexes. The combination of index types determines how the compound index matches documents.复合索引可以包含不同类型的稀疏索引。索引类型的组合决定了复合索引如何匹配文档。

This table summarizes the behavior of a compound index that contains different types of sparse indexes:此表总结了包含不同类型稀疏索引的复合索引的行为:

Compound Index Components复合指数成分Compound Index Behavior复合指数行为
Ascending indexes升序索引
Descending indexes降序索引
Only indexes documents that contain a value for at least one of the keys.仅对包含至少一个键的值的文档进行索引。
Ascending indexes升序索引
Descending indexes降序索引
Geospatial indexes地理空间索引
Only indexes a document when it contains a value for one of the geospatial fields. Does not index documents in the ascending or descending indexes.仅当文档包含其中一个geospatial字段的值时,才对文档进行索引。不按升序或降序索引对文档进行索引。
Ascending indexes升序索引
Descending indexes降序索引
Text indexes全文索引
Only indexes a document when it matches one of the text fields. Does not index documents in the ascending or descending indexes.仅当文档与其中一个text字段匹配时,才对其进行索引。不按升序或降序索引对文档进行索引。

Learn More了解更多

To learn how to create efficient compound indexes, see The ESR (Equality, Sort, Range) Guideline.要了解如何创建高效的复合索引,请参阅ESR(相等、排序、范围)指南。