选择语言
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
字段。
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来完成。
➤ 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 in the Mongo Shell, use 要在Mongo Shell中创建索引,请使用db.collection.createIndex()
.db.collection.createIndex()
。
db.collection.createIndex( <key and index type specification>, <options> )
The following example creates a single key descending index on the 以下示例在name
field:name
字段上创建一个单键降序索引:
db.collection.createIndex( { name: -1 } )
The db.collection.createIndex()
method only creates an index if an index of the same specification does not already exist.db.collection.createIndex()
方法仅在相同规范的索引不存在时创建索引。
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 left-hand MongoDB Compass navigation pane, click the database that contains your desired collection.在左侧的MongoDB Compass导航窗格中,单击包含所需集合的数据库。
From the database view, click the target collection name.在数据库视图中,单击目标集合名称。
Compass supports the following index options:Compass支持以下索引选项:
Create TTL | ||
{ "timezone": { "$exists": true } } | ||
To create an index using the .NET driver, use MongoCollection.CreateIndex.
collection.CreateIndex( IndexKeys<collection>.<key and index type specification>, <options> );
The following example creates a single key descending index on the name
field:
collection.CreateIndex( IndexKeys<collection>.Descending("name") );
The MongoCollection.CreateIndex method only creates an index if an index of the same specification does not already exist.
To create an index using the Async Java driver, use com.mongodb.async.client.MongoCollection.createIndex.
collection.createIndex( <key and index type specification>, <options>, <callbackFunction>)
The following example creates a single key descending index on the name
field:
collection.createIndex(Indexes.descending("name"), someCallbackFunction());
The com.mongodb.async.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 Java driver, use com.mongodb.client.MongoCollection.createIndex.
collection.createIndex( <key and index type specification>, <options> )
The following example creates a single key descending index on the name
field:
collection.createIndex(Indexes.descending("name"));
The 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 Motor driver, use motor.motor_asyncio.AsyncIOMotorCollection.create_index
.
await db.collection.create_index([(<key and index type specification>)], <options> )
The following example creates a single key descending index on the name
field:
await collection.create_index([("name", pymongo.DESCENDING)])
The motor.motor_asyncio.AsyncIOMotorCollection.create_index
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 要使用Node.JS驱动程序创建索引,请使用createIndex()
.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()
方法仅在相同规范的索引不存在时创建索引。
To create an index using the Perl driver, use create_one().
my $indexes = $db->get_collection( <collection> )->indexes; $indexes->create_one( [ <key and index type specification> ] );
The following example creates a single key descending index on the name
field:
my $indexes = $db->get_collection( <collection> )->indexes; $indexes->create_one( [ name => -1 ] );
The create_one() method only creates an index if an index of the same specification does not already exist.
To create an index using the PHP driver, use MongoDB\\Collection::createIndex()
.
$collection->createIndex(<key and index type specification>, <options>);
The following example creates a single key descending index on the name
field:
$collection->createIndex(['name' => -1]);
The MongoDB\\Collection::createIndex()
method only creates an index if an index of the same specification does not already exist.
To create an index using the Python driver, use pymongo.collection.Collection.create_index
.
db.collection.create_index([(<key and index type specification>)], <options> )
The following example creates a single key descending index on the name
field:
collection.create_index([("name", pymongo.DESCENDING)])
The pymongo.collection.Collection.create_index
method only creates an index if an index of the same specification does not already exist.
To create an index using the Ruby driver, use Mongo::Index::View#create_one.
client[:collection].indexes.create_one({ <key and index type specification> }, {options})
The following example creates a single key descending index on the name
field:
client[:collection].indexes.create_one({ name: -1 })
The Mongo::Index::View#create_one method only creates an index if an index of the same specification does not already exist.
To create an index using the Scala driver, use org.mongodb.scala.model.Indexes.
collection.createIndex(<key and index type specification>)
The following example creates a single key descending index on the name
field:
collection.createIndex(descending("name"))
The org.mongodb.scala.model.Indexes method only creates an index if an index of the same specification does not already exist.
[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
的item
和quantity
索引:
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.相反,您必须删除并使用新名称重新创建索引。
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.除了唯一约束之外,唯一索引在功能上可以与其他MongoDB索引互换。
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. 索引的sparse
属性确保索引仅包含具有索引字段的文档的条目。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. 是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使集合中的数据过期以获取实现说明。
New in version 4.4.在版本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
索引之外,您可以隐藏任何索引。
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如何选择要使用的索引的信息,请参阅查询优化器。
Collation排序规则 allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.允许用户为字符串比较指定特定于语言的规则,例如大小写和重音符号的规则。
➤ Use the Select your language drop-down menu in the upper-right to set the language of the examples on this page.使用右上角的“选择您的语言”下拉菜单设置此页面上示例的语言。
The following examples illustrate indexes and collation in 以下示例说明了mongosh
.mongosh
中的索引和排序。
Refer to the MongoDB Compass Documentation for instructions on using custom collation with indexes in Compass.请参阅MongoDB Compass文档,了解如何在Compass中使用索引的自定义排序规则。
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.有关在特定驱动程序中使用排序规则创建索引的说明,请参阅驱动程序文档。
The following examples illustrate indexes and collation in mongosh
.
Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.
The following examples illustrate indexes and collation in mongosh
.
Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.
The following examples illustrate indexes and collation in mongosh
.
Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.
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.有关在特定驱动程序中使用排序规则创建索引的说明,请参阅驱动程序文档。
The following examples illustrate indexes and collation in mongosh
.
Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.
The following examples illustrate indexes and collation in mongosh
.
Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.
The following examples illustrate indexes and collation in mongosh
.
Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.
The following examples illustrate indexes and collation in mongosh
.
Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.
The following examples illustrate indexes and collation in 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
在数字字段score
和price
以及字符串字段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:以下索引仅支持简单的二进制比较,不支持排序规则:
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.这对结果索引没有任何影响。