Docs HomeMongoDB Manual

Indexes索引

Indexes support the efficient execution of queries in MongoDB. 索引支持MongoDB中查询的高效执行。Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement. 在没有索引的情况下,MongoDB必须执行集合扫描,即扫描集合中的每个文档,以选择与查询语句匹配的文档。If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.如果查询存在适当的索引,MongoDB可以使用该索引来限制它必须检查的文档数量。

Indexes are special data structures [1] that store a small portion of the collection's data set in an easy to traverse form. 索引是一种特殊的数据结构[1],它以易于遍历的形式存储集合数据集的一小部分。The index stores the value of a specific field or set of fields, ordered by the value of the field. 索引存储特定字段或字段集的值,按字段值排序。The ordering of the index entries supports efficient equality matches and range-based query operations. 索引项的排序支持高效的相等匹配和基于范围的查询操作。In addition, MongoDB can return sorted results by using the ordering in the index.此外,MongoDB可以通过使用索引中的排序来返回排序后的结果。

The following diagram illustrates a query that selects and orders the matching documents using an index:下图显示了一个使用索引选择和排序匹配文档的查询:

Diagram of a query that uses an index to select and return sorted results. The index stores ``score`` values in ascending order. MongoDB can traverse the index in either ascending or descending order to return sorted results.

Fundamentally, indexes in MongoDB are similar to indexes in other database systems. 从根本上讲,MongoDB中的索引与其他数据库系统中的索引相似。MongoDB defines indexes at the collection level and supports indexes on any field or sub-field of the documents in a MongoDB collection.MongoDB在集合级别定义索引,并支持MongoDB集合中文档的任何字段或子字段上的索引。

Default _id Index默认索引_id

MongoDB creates a unique index on the _id field during the creation of a collection. 在创建集合的过程中,MongoDB会在_id字段上创建一个唯一的索引The _id index prevents clients from inserting two documents with the same value for the _id field. You cannot drop this index._id索引防止客户端插入两个具有相同_id字段值的文档。不能删除此索引。

Note

In sharded clusters, if you do not use the _id field as the shard key, then your application must ensure the uniqueness of the values in the _id field. 分片集群中,如果不使用_id字段作为分片键,那么应用程序必须确保_id字段中值的唯一性。You can do this by using a field with an auto-generated ObjectId.您可以通过使用具有自动生成的 ObjectId的字段来完成此操作。

Create an Index创建索引


➤ Use the Select your language drop-down menu in the upper-right to set the language of the examples on this page.


To create an index using the Node.JS driver, use createIndex().要使用NodeJS驱动程序创建索引,请使用createIndex()

collection.createIndex( { <key and index type specification> }, function(err, result) {
console.log(result);
callback(result);
}

The following example creates a single key descending index on the name field:以下示例在name字段上创建一个单键降序索引:

 collection.createIndex( { name : -1 }, function(err, result) {
console.log(result);
callback(result);
}

The createIndex() method only creates an index if an index of the same specification does not already exist.createIndex()方法仅在不存在相同规范的索引的情况下创建索引。

[1] MongoDB indexes use a B-tree data structure.MongoDB索引使用B树数据结构。

Index Names索引名称

The default name for an index is the concatenation of the indexed keys and each key's direction in the index ( i.e. 1 or -1) using underscores as a separator. 索引的默认名称是索引键和索引中每个键的方向(即-1或-1)的串联,使用下划线作为分隔符。For example, an index created on { item : 1, quantity: -1 } has the name item_1_quantity_-1.例如,在{ item : 1, quantity: -1 }上创建的索引的名称为item_1_quantity_-1

You can create indexes with a custom name, such as one that is more human-readable than the default. 您可以使用自定义名称创建索引,例如比默认名称更易于阅读的索引。For example, consider an application that frequently queries the products collection to populate data on existing inventory. 例如,考虑一个经常查询products集合以填充现有库存数据的应用程序。The following createIndex() method creates an index on item and quantity named query for inventory:下面的createIndex()方法在itemquantity上创建索引,名为query for inventory

db.products.createIndex(
{ item: 1, quantity: -1 } ,
{ name: "query for inventory" }
)

You can view index names using the db.collection.getIndexes() method. 可以使用db.collection.getIndexes()方法查看索引名称。You cannot rename an index once created. Instead, you must drop and re-create the index with a new name.索引一旦创建,就不能重命名。相反,您必须删除索引并使用新名称重新创建索引。

Index Types索引类型

MongoDB provides a number of different index types to support specific types of data and queries.MongoDB提供了许多不同的索引类型来支持特定类型的数据和查询。

Single Field单个字段

In addition to the MongoDB-defined _id index, MongoDB supports the creation of user-defined ascending/descending indexes on a single field of a document.除了MongoDB定义的_id索引外,MongoDB还支持在文档的单个字段上创建用户定义的升序/降序索引。

Diagram of an index on the ``score`` field (ascending).

For a single-field index and sort operations, the sort order (i.e. ascending or descending) of the index key does not matter because MongoDB can traverse the index in either direction.对于单个字段的索引和排序操作,索引键的排序顺序(即升序或降序)并不重要,因为MongoDB可以在任意方向遍历索引。

See Single Field Indexes and Sort with a Single Field Index for more information on single-field indexes.有关单字段索引的详细信息,请参阅单字段索引使用单字段索引排序

Compound Index复合指数

MongoDB also supports user-defined indexes on multiple fields, i.e. compound indexes.MongoDB还支持多个字段上的用户定义索引,即复合索引

The order of fields listed in a compound index has significance. 在复合索引中列出的字段的顺序具有重要意义。For instance, if a compound index consists of { userid: 1, score: -1 }, the index sorts first by userid and then, within each userid value, sorts by score.例如,如果复合索引由{ userid: 1, score: -1 }组成,则该索引首先按userid排序,然后在每个userid值内按score排序。

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.

For compound indexes and sort operations, the sort order (i.e. ascending or descending) of the index keys can determine whether the index can support a sort operation. 对于复合索引和排序操作,索引键的排序顺序(即升序或降序)可以决定索引是否支持排序操作。See Sort Order for more information on the impact of index order on results in compound indexes.有关索引顺序对复合索引中结果的影响的详细信息,请参阅排序顺序

See also:另请参阅:

Multikey Index多键索引

MongoDB uses multikey indexes to index the content stored in arrays. MongoDB使用多键索引对存储在数组中的内容进行索引。If you index a field that holds an array value, MongoDB creates separate index entries for every element of the array. 如果对包含数组值的字段进行索引,MongoDB会为数组的每个元素创建单独的索引条目。These multikey indexes allow queries to select documents that contain arrays by matching on element or elements of the arrays. 这些多键索引允许查询通过匹配数组的一个或多个元素来选择包含数组的文档。MongoDB automatically determines whether to create a multikey index if the indexed field contains an array value; you do not need to explicitly specify the multikey type.如果索引字段包含数组值,MongoDB会自动确定是否创建多键索引;您不需要显式指定多密钥类型。

Diagram of a multikey index on the ``addr.zip`` field. The ``addr`` field contains an array of address documents. The address documents contain the ``zip`` field.

See Multikey Indexes and Multikey Index Bounds for more information on multikey indexes.有关多键索引的详细信息,请参阅多键索引多键索引边界

Geospatial Index地理空间索引

To support efficient queries of geospatial coordinate data, MongoDB provides two special indexes: 2d indexes that uses planar geometry when returning results and 2dsphere indexes that use spherical geometry to return results.为了支持高效查询地理空间坐标数据,MongoDB提供了两个特殊的索引:在返回结果时使用平面几何体的2d索引和使用球面几何体返回结果的2dsphere索引

This index is a sparse index. 此索引是稀疏索引If you want to use a sparse index to create a compound index, first review the special considerations of using sparse compound indexes.如果要使用稀疏索引创建复合索引,请首先查看使用稀疏复合索引的特殊注意事项。

See Geospatial Indexes for a high level introduction to geospatial indexes.有关地理空间索引的高级介绍,请参阅地理空间索引

Text Search Indexes文本搜索索引

For data hosted on MongoDB Atlas, you can support full-text search with Atlas Search indexes. 对于MongoDB Atlas上托管的数据,您可以使用Atlas search索引支持全文搜索。To learn more, see Create an Atlas Search Index.要了解更多信息,请参阅创建Atlas搜索索引

For self-managed (non-Atlas) deployments, MongoDB provides a text index type that supports searching for string content in a collection. 对于自管理(非Atlas)部署,MongoDB提供了一种text索引类型,支持搜索集合中的字符串内容。To learn more about self-managed text indexes, see Text Indexes.要了解有关自管理文本索引的更多信息,请参阅文本索引

This index is a sparse index. 此索引是稀疏索引If you want to use a sparse index to create a compound index, first review the special considerations of using sparse compound indexes.如果要使用稀疏索引创建复合索引,请首先查看使用稀疏复合索引的特殊注意事项。

Hashed Indexes哈希索引

To support hash based sharding, MongoDB provides a hashed index type, which indexes the hash of the value of a field. 为了支持基于哈希的分片,MongoDB提供了一种哈希索引类型,它对字段值的哈希进行索引。These indexes have a more random distribution of values along their range, but only support equality matches and cannot support range-based queries.这些索引的值在其范围内的分布更加随机,但只支持相等匹配,不能支持基于范围的查询。

Clustered Indexes群集索引

Starting in MongoDB 5.3, you can create a collection with a clustered index. 从MongoDB 5.3开始,您可以创建一个具有聚集索引的集合。Collections created with a clustered index are called clustered collections.使用聚集索引创建的集合称为聚集集合。

See Clustered Collections.请参见聚集集合

Wildcard Indexes通配符索引

Starting in MongoDB 4.2, you can use wildcard indexes to support queries against multiple, arbitrary, or unknown fields. 从MongoDB 4.2开始,您可以使用通配符索引来支持针对多个、任意或未知字段的查询。When you create a wildcard index, you specify $** to represent all fields or all values, allowing you to index any of the following with a single command:创建通配符索引时,您可以指定$**来表示所有字段或所有值,从而可以使用单个命令对以下任何项进行索引:

  • All values of a field字段的所有值

  • All fields in a document文档中的所有字段

  • All fields in a document except specific field paths文档中除特定字段路径之外的所有字段

  • Multiple specific fields in a document文档中的多个特定字段

To learn more, see Wildcard Indexes.要了解更多信息,请参阅通配符索引

Index Properties索引属性

Unique Indexes唯一索引

The unique property for an index causes MongoDB to reject duplicate values for the indexed field. 索引的unique属性导致MongoDB拒绝索引字段的重复值。Other than the unique constraint, unique indexes are functionally interchangeable with other MongoDB indexes.除了唯一约束之外,唯一索引在功能上可以与其他MongoDB索引互换。

Partial Indexes部分索引

Partial indexes only index the documents in a collection that meet a specified filter expression. 分部索引仅对集合中符合指定筛选表达式的文档进行索引。By indexing a subset of the documents in a collection, partial indexes have lower storage requirements and reduced performance costs for index creation and maintenance.通过对集合中的文档子集进行索引,部分索引可以降低存储需求,并降低索引创建和维护的性能成本。

Partial indexes offer a superset of the functionality of sparse indexes and should be preferred over sparse indexes.部分索引提供了稀疏索引功能的超集,应该优先于稀疏索引。

Sparse Indexes稀疏索引

The sparse property of an index ensures that the index only contains entries for documents that have the indexed field. The index skips documents that do not have the indexed field.索引的sparse属性确保索引只包含具有索引字段的文档的条目。索引会跳过没有索引字段的文档。

You can combine the sparse index option with the unique index option to prevent inserting documents that have duplicate values for the indexed field(s) and skip indexing documents that lack the indexed field(s).您可以将sparse索引选项与unique索引选项结合使用,以防止插入索引字段值重复的文档,并跳过对缺少索引字段的文档进行索引。

TTL IndexesTTL索引

TTL indexes automatically remove documents from a collection after a certain amount of time. TTL索引会在一定时间后自动从集合中删除文档。This is ideal for certain types of information like machine generated event data, logs, and session information that only need to persist in a database for a finite amount of time.这非常适合某些类型的信息,如机器生成的事件数据、日志和会话信息,这些信息只需要在数据库中保留有限的时间。

See: Expire Data from Collections by Setting TTL for implementation instructions.有关实现说明,请参阅:通过设置TTL使集合中的数据过期

Hidden Indexes隐藏索引

New in version 4.4.

Hidden indexes are not visible to the query planner and cannot be used to support a query.隐藏索引查询计划器不可见,不能用于支持查询。

By hiding an index from the planner, users can evaluate the potential impact of dropping an index without actually dropping the index. 通过向计划器隐藏索引,用户可以在不实际删除索引的情况下评估删除索引的潜在影响。If the impact is negative, the user can unhide the index instead of having to recreate a dropped index. 如果影响是负面的,用户可以取消隐藏索引,而不必重新创建已删除的索引。And because indexes are fully maintained while hidden, the indexes are immediately available for use once unhidden.由于索引在隐藏时是完全维护的,因此一旦取消隐藏,索引就可以立即使用。

Except for the _id index, you can hide any indexes.除了_id索引之外,您可以隐藏任何索引。

Index Use索引使用

Indexes can improve the efficiency of read operations. 索引可以提高读取操作的效率。The Analyze Query Performance tutorial provides an example of the execution statistics of a query with and without an index.分析查询性能教程提供了一个带索引和不带索引的查询的执行统计信息示例。

For information on how MongoDB chooses an index to use, see query optimizer.有关MongoDB如何选择要使用的索引的信息,请参阅查询优化器

Indexes and Collation索引和排序

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.排序规则允许用户为字符串比较指定特定于语言的规则,例如大小写和重音标记的规则。

Note

The following examples illustrate indexes and collation in mongosh.以下示例说明了mongosh中的索引和排序规则。

Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.有关在特定驱动程序中使用排序规则创建索引的说明,请参阅驱动程序文档

To use an index for string comparisons, an operation must also specify the same collation. 若要使用索引进行字符串比较,操作还必须指定相同的排序规则。That is, an index with a collation cannot support an operation that performs string comparisons on the indexed fields if the operation specifies a different collation.也就是说,如果具有排序规则的索引指定了不同的排序规则,则该索引无法支持对索引字段执行字符串比较的操作。

For example, the collection myColl has an index on a string field category with the collation locale "fr".例如,集合myColl在排序规则区域设置为"fr"的字符串字段category上有一个索引。

db.myColl.createIndex( { category: 1 }, { collation: { locale: "fr" } } )

The following query operation, which specifies the same collation as the index, can use the index:以下查询操作指定与索引相同的排序规则,可以使用索引:

db.myColl.find( { category: "cafe" } ).collation( { locale: "fr" } )

However, the following query operation, which by default uses the "simple" binary collator, cannot use the index:但是,以下查询操作(默认情况下使用“简单”二进制排序器)不能使用索引:

db.myColl.find( { category: "cafe" } )

For a compound index where the index prefix keys are not strings, arrays, and embedded documents, an operation that specifies a different collation can still use the index to support comparisons on the index prefix keys.对于索引前缀键不是字符串、数组和嵌入文档的复合索引,指定不同排序规则的操作仍然可以使用索引来支持对索引前缀键的比较。

For example, the collection myColl has a compound index on the numeric fields score and price and the string field category; the index is created with the collation locale "fr" for string comparisons:例如,集合myColl对数字字段scoreprice以及字符串字段category有一个复合索引;索引是使用排序规则区域设置“fr”创建的,用于字符串比较:

db.myColl.createIndex(
{ score: 1, price: 1, category: 1 },
{ collation: { locale: "fr" } } )

The following operations, which use "simple" binary collation for string comparisons, can use the index:以下操作使用"simple"二进制排序规则进行字符串比较,可以使用索引:

db.myColl.find( { score: 5 } ).sort( { price: 1 } )
db.myColl.find( { score: 5, price: { $gt: NumberDecimal( "10" ) } } ).sort( { price: 1 } )

The following operation, which uses "simple" binary collation for string comparisons on the indexed category field, can use the index to fulfill only the score: 5 portion of the query:以下操作使用"simple"二进制排序规则对索引category字段进行字符串比较,可以使用索引仅完成查询的score: 5部分:

db.myColl.find( { score: 5, category: "cafe" } )

For more information on collation, see the collation reference page.有关排序规则的详细信息,请参阅排序规则参考页

The following indexes only support simple binary comparison and do not support collation:以下索引仅支持简单的二进制比较,不支持排序规则

  • text indexes,索引,

  • 2d indexes, and索引,以及

  • geoHaystack indexes.索引。

Covered Queries涵盖的查询

When the query criteria and the projection of a query include only the indexed fields, MongoDB returns results directly from the index without scanning any documents or bringing documents into memory. 当查询条件和查询投影仅包括索引字段时,MongoDB直接从索引返回结果,而无需扫描任何文档或将文档带入内存。These covered queries can be very efficient.这些涵盖的查询可能非常高效。

Diagram of a query that uses only the index to match the query criteria and return the results. MongoDB does not need to inspect data outside of the index to fulfill the query.

For more information on covered queries, see Covered Query.有关覆盖查询的更多信息,请参阅覆盖查询

Index Intersection索引交叉点

MongoDB can use the intersection of indexes to fulfill queries. MongoDB可以使用索引的交集来完成查询。For queries that specify compound query conditions, if one index can fulfill a part of a query condition, and another index can fulfill another part of the query condition, then MongoDB can use the intersection of the two indexes to fulfill the query. 对于指定复合查询条件的查询,如果一个索引可以满足一个查询条件的一部分,而另一个索引则可以满足查询条件的另一部分,则MongoDB可以使用这两个索引的交集来实现查询。Whether the use of a compound index or the use of an index intersection is more efficient depends on the particular query and the system.使用复合索引还是使用索引交集更有效取决于特定的查询和系统。

For details on index intersection, see Index Intersection.有关索引交点的详细信息,请参阅索引交点

Restrictions限制

Certain restrictions apply to indexes, such as the length of the index keys or the number of indexes per collection. 某些限制适用于索引,例如索引键的长度或每个集合的索引数。See Index Limitations for details.有关详细信息,请参阅索引限制

Additional Considerations其他注意事项

Although indexes can improve query performances, indexes also present some operational considerations. 尽管索引可以提高查询性能,但索引也提供了一些操作注意事项。See Operational Considerations for Indexes for more information.有关详细信息,请参阅索引的操作注意事项

During index builds, applications may encounter reduced performance or limited read/write access to the collection being indexed.在索引构建过程中,应用程序可能会遇到性能下降或对正在索引的集合的读/写访问受限的情况。

For more information on the index build process, see Index Builds on Populated Collections, especially the Index Builds in Replicated Environments section.有关索引生成过程的详细信息,请参阅填充集合上的索引生成,特别是复制环境中的索引生成部分

Some drivers use NumberLong(1) instead of 1 to specify the index order. 一些驱动程序使用NumberLong(1)而不是1来指定索引顺序。The resulting indexes are the same.生成的索引是相同的。