On this page本页内容
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:下图演示了使用索引选择和排序匹配文档的查询:
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集合中文档的任何字段或子字段的索引。
_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._id
索引防止客户端为_id
字段插入具有相同值的两个文档。You cannot drop this index on the 不能丢弃_id
field._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 to prevent errors._id
字段作为分片键,那么您的应用程序必须确保_id
字段中的值的唯一性以防止错误。This is most-often done by using a standard auto-generated ObjectId.这通常是通过使用标准的自动生成的ObjectId来实现的。
To create an index in the Mongo Shell, use 要在db.collection.createIndex()
.Mongo
Shell中创建索引,请使用db.collection.createIndex()
创建索引。
The following example creates a single key descending index on the 以下示例在name
field:name
字段上创建单键降序索引:
The 这个db.collection.createIndex
method only creates an index if an index of the same specification does not already exist.db.collection.createIndex
创建索引方法仅在同一规范的索引不存在时创建索引。
Important
To create an index on a collection in MongoDB Compass, the collection must contain documents.要在MongoDB Compass中的集合上创建索引,该集合必须包含文档。
To create an index in MongoDB Compass:要在MongoDB Compass中创建索引,请执行以下操作:
In the dialog, enter the name of the index to create, or leave blank to have MongoDB create a default name for the index.在对话框中,输入要创建的索引的名称,或保留为空以让MongoDB为索引创建默认名称。
To specify a key for the index, select the field and the index type.要为索引指定键,请选择字段和索引类型。To index additional fields, click Add Another Field.若要索引其他字段,请单击“添加其他字段”。
Compass supports the following index options:罗盘支持以下索引选项:
TTL Indexes | ||
|
||
To create an index using the Python driver, use 要使用Python驱动程序创建索引,请使用pymongo.collection.Collection.create_index()
.pymongo.collection.Collection.create_index()
。
The following example creates a single key descending index on the 以下示例在name
field:name
字段上创建单键降序索引:
The 这个pymongo.collection.Collection.create_index()
method only creates an index if an index of the same specification does not already exist.pymongo.collection.Collection.create_index()
方法仅在同一规范的索引不存在时创建索引。
To create an index using the Java driver, use com.mongodb.client.MongoCollection.createIndex.要使用Java驱动程序创建索引,请使用com.mongodb.client.MongoCollection.createIndex。
The following example creates a single key descending index on the 以下示例在name
field:name
字段上创建单键降序索引:
The com.mongodb.client.MongoCollection.createIndex.这个com.mongodb.client.MongoCollection.createIndex。method only creates an index if an index of the same specification does not already exist.方法仅在同一规范的索引不存在时创建索引。
To create an index using the Node.JS driver, use createIndex().要使用Node.js驱动程序创建索引,请使用createIndex()。
The following example creates a single key descending index on the 以下示例在name
field:name
字段上创建单键降序索引:
The createIndex() method only creates an index if an index of the same specification does not already exist.createIndex()
方法仅在同一规范的索引不存在时创建索引。
To create an index using the PHP driver, use 要使用PHP驱动程序创建索引,请使用MongoDB\Collection::createIndex()
.MongoDB\Collection::createIndex()
。
The following example creates a single key descending index on the 以下示例在name
field:name
字段上创建单键降序索引:
The MongoDB\Collection::createIndex()
method only creates an index if an index of the same specification does not already exist.MongoDB\Collection::createIndex()
方法仅在同一规范的索引不存在时创建索引。
To create an index using the Motor driver, use 要使用Motor驱动程序创建索引,请使用motor.motor_asyncio.AsyncIOMotorCollection.create_index()
.motor.motor_asyncio.AsyncIOMotorCollection.create_index()
。
The following example creates a single key descending index on the 以下示例在name
field:name
字段上创建单键降序索引:
The 这个motor.motor_asyncio.AsyncIOMotorCollection.create_index()
method only creates an index if an index of the same specification does not already exist.motor.motor_asyncio.AsyncIOMotorCollection.create_index()
方法仅在同一规范的索引不存在时创建索引。
To create an index using the Async Java driver, use com.mongodb.async.client.MongoCollection.createIndex.要使用异步Java驱动程序创建索引,请使用com.mongodb.async.client.MongoCollection.createIndex。
The following example creates a single key descending index on the 以下示例在name
field:name
字段上创建单键降序索引:
The com.mongodb.async.client.MongoCollection.createIndex method only creates an index if an index of the same specification does not already exist.这个com.mongodb.async.client.MongoCollection.createIndex方法仅在同一规范的索引不存在时创建索引。
To create an index using the .NET driver, use MongoCollection.CreateIndex.要使用.NET驱动程序创建索引,请使用MongoCollection.CreateIndex。
The following example creates a single key descending index on the 以下示例在name
field:name
字段上创建单键降序索引:
The MongoCollection.CreateIndex method only creates an index if an index of the same specification does not already exist.这个MongoCollection.CreateIndex方法仅在同一规范的索引不存在时创建索引。
To create an index using the Perl driver, use create_one().要使用Perl驱动程序创建索引,请使用create_one()。
The following example creates a single key descending index on the 以下示例在name
field:name
字段上创建单键降序索引:
The create_one() method only creates an index if an index of the same specification does not already exist.create_one()方法仅在同一规范的索引不存在时创建索引。
To create an index using the Ruby driver, use Mongo::Index::View#create_one.要使用Ruby驱动程序创建索引,请使用Mongo::Index::View#create_one。
The following example creates a single key descending index on the 以下示例在name
field:name
字段上创建单键降序索引:
The Mongo::Index::View#create_one method only creates an index if an index of the same specification does not already exist.Mongo::Index::View#create_one方法仅在同一规范的索引不存在时创建索引。
To create an index using the Scala driver, use org.mongodb.scala.model.Indexes.要使用Scala驱动程序创建索引,请使用org.mongodb.scala.model.Indexes。
The following example creates a single key descending index on the 以下示例在name
field:name
字段上创建单键降序索引:
The org.mongodb.scala.model.Indexes method only creates an index if an index of the same specification does not already exist.这个org.mongodb.scala.model.Indexes方法仅在同一规范的索引不存在时创建索引。
[1] |
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()
方法创建名为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.相反,必须删除并用新名称重新创建索引。
MongoDB provides a number of different index types to support specific types of data and queries.MongoDB提供了许多不同的索引类型来支持特定类型的数据和查询。
In addition to the MongoDB-defined 除了MongoDB定义的_id
index, MongoDB supports the creation of user-defined ascending/descending indexes on a single field of a document._id
索引之外,MongoDB还支持在文档的单个字段上创建用户定义的升序/降序索引。
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.有关单字段索引的详细信息,请参见单字段索引和使用单字段索引排序。
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
排序。
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 Compound Indexes and Sort on Multiple Fields for more information on compound indexes.有关复合索引的详细信息,请参见复合索引和对多个字段排序。
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会自动确定是否创建多键索引;您不需要显式指定多键类型。
See Multikey Indexes and Multikey Index Bounds for more information on multikey indexes.有关多键索引的详细信息,请参见多键索引和多键索引边界。
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索引。
See 2d Index Internals for a high level introduction to geospatial indexes.有关地理空间索引的高级介绍,请参见2d索引内部构件。
MongoDB provides a MongoDB提供了一种text
index type that supports searching for string content in a collection.text
索引类型,支持在集合中搜索字符串内容。These text indexes do not store language-specific stop words (e.g. “the”, “a”, “or”) and stem the words in a collection to only store root words.这些文本索引不存储特定于语言的停止词(例如“the”、“a”、“or”),而是将集合中的词干仅存储根词。
See Text Indexes for more information on text indexes and search.有关文本索引和搜索的详细信息,请参见文本索引。
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.这些索引的值沿其范围的分布更为随机,但只支持相等匹配,不支持基于范围的查询。
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.除了unique约束之外,unique索引在功能上可以与其他MongoDB索引互换。
New in version 3.2.版本3.2中的新功能。
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.部分索引提供了稀疏索引功能的超集,应该优先于稀疏索引。
The sparse property of an index ensures that the index only contain entries for documents that have the indexed field.索引的稀疏属性确保索引只包含具有索引字段的文档的条目。The index skips documents that do not have the indexed field.索引跳过没有索引字段的文档。
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).可以将“稀疏索引”选项与“唯一索引”选项结合使用,以防止插入索引字段值重复的文档,并跳过缺少索引字段的索引文档。
TTL indexes are special indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time.TTL索引是MongoDB可以用来在一定时间后自动从集合中删除文档的特殊索引。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使集合中的数据过期。
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如何选择要使用的索引的信息,请参阅查询优化器。
New in version 3.4.版本3.4中的新功能。
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 the Mongo Shell.下面的示例说明Mongo shell中的索引和排序规则。
Refer to the MongoDB Compass Documentation for instructions on using custom collation with indexes in Compass.请参阅MongoDB compass文档,以获取有关在Compass中使用带有索引的自定义排序规则的说明。
Note
The following examples illustrate indexes and collation in the Mongo Shell.
Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.
Note
The following examples illustrate indexes and collation in the Mongo Shell.
Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.
Note
The following examples illustrate indexes and collation in the Mongo Shell.
Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.
Note
The following examples illustrate indexes and collation in the Mongo Shell.
Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.
Note
The following examples illustrate indexes and collation in the Mongo Shell.
Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.
Note
The following examples illustrate indexes and collation in the Mongo Shell.
Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.
Note
The following examples illustrate indexes and collation in the Mongo Shell.
Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.
Note
The following examples illustrate indexes and collation in the Mongo Shell.
Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.
Note
The following examples illustrate indexes and collation in the Mongo Shell.
Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.
Note
The following examples illustrate indexes and collation in the Mongo Shell.
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
上有一个索引。
The following query operation, which specifies the same collation as the index, can use the index:以下查询操作指定与索引相同的排序规则,可以使用索引:
However, the following query operation, which by default uses the “simple” binary collator, cannot use the index:但是,以下查询操作(默认情况下使用“简单”二进制整理机)不能使用索引:
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
在数值字段score
和price
以及字符串字段category
上有一个复合索引;该索引是使用排序规则区域设置"fr"
创建的,用于字符串比较:
The following operations, which use 使用"simple"
binary collation for string comparisons, can use the index:"simple"
二进制排序规则进行字符串比较的以下操作可以使用索引:
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
部分:
For more information on collation, see the collation reference page.有关排序规则的详细信息,请参阅排序规则参考页。
The following indexes only support simple binary comparison and do not support collation:以下索引仅支持简单的二进制比较,不支持排序规则:
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.这些包含的查询可能非常有效。
For more information on covered queries, see Covered Query.有关覆盖查询的详细信息,请参见覆盖查询。
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.有关索引交点的详细信息,请参见索引交点。
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.有关详细信息,请参见索引约束。
Although indexes can improve query performances, indexes also present some operational considerations.虽然索引可以提高查询性能,但索引也提供了一些操作方面的考虑。See Operational Considerations for Indexes for more information.有关详细信息,请参阅索引的操作注意事项。
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.这对结果索引没有任何影响。