Indexes索引

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:下图演示了使用索引选择和排序匹配文档的查询:

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._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来实现的。

Create an Index创建索引

To create an index in the Mongo Shell, use db.collection.createIndex().要在Mongo Shell中创建索引,请使用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创建索引方法仅在同一规范的索引不存在时创建索引。

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中创建索引,请执行以下操作:

1
2

Click the Create Index button.单击“创建索引”按钮。

From the Indexes tab, click the Create Index button to bring up the Create Index dialog.“索引”选项卡中,单击“创建索引”按钮以打开“创建索引”对话框。

3

Optional.可选。Enter the index name.输入索引名称。

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为索引创建默认名称。

4

Add fields to index.将字段添加到索引。

To specify a key for the index, select the field and the index type.要为索引指定键,请选择字段和索引类型。To index additional fields, click Add Another Field.若要索引其他字段,请单击“添加其他字段”。

5

Optional.可选。Specify the index options.指定索引选项。

Compass supports the following index options:罗盘支持以下索引选项:

Option选项Description说明More Information更多信息
Build index in the background在后台建立索引 If checked, ensure that the MongoDB deployment remains available during the index build operation.如果选中,请确保MongoDB部署在索引生成操作期间仍然可用。 Background Construction背景结构
Create unique index创建唯一索引 If checked, ensure that the indexed fields do not store duplicate values.如果选中,请确保索引字段不存储重复的值。 Unique Indexes唯一索引
Create创建TTL If checked, automatically delete documents after a specified number of seconds since the indexed field value.如果选中,则在指定的秒数(从索引字段值开始)后自动删除文档。 TTL Indexes
Partial filter expression部分筛选表达式

If checked, only index documents which match the specified filter expression.如果选中,则仅索引与指定筛选器表达式匹配的文档。

For example, the following partial filter expression only indexes documents where the timezone field exists:例如,以下部分筛选器表达式仅对存在timezone字段的文档编制索引:

{ "timezone": { "$exists": true } }
Partial Indexes部分索引
Use custom collation使用自定义排序规则 If checked, create a custom collation for the index using the options provided in Compass.如果选中,请使用Compass中提供的选项为索引创建自定义排序规则。 Collation Document整理文件
Wildcard projection通配符投影 (New in MongoDB 4.2MongoDB 4.2中的新功能) If checked, support unknown or arbitrary fields which match the specified projection in the index.如果选中,则支持与索引中指定投影匹配的未知或任意字段。 Wildcard Indexes通配符索引
6

Click Create to create the index.单击“创建”创建索引。

To create an index using the Python driver, use pymongo.collection.Collection.create_index().要使用Python驱动程序创建索引,请使用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:以下示例在name字段上创建单键降序索引:

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.这个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

collection.createIndex( <key and index type specification>, <options> )

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

collection.createIndex(Indexes.descending("name"));

The com.mongodb.client.MongoCollection.createIndex.这个com.mongodb.client.MongoCollection.createIndexmethod 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()

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 PHP driver, use MongoDB\Collection::createIndex().要使用PHP驱动程序创建索引,请使用MongoDB\Collection::createIndex()

$collection->createIndex(<key and index type specification>, <options>);

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

$collection->createIndex(['name' => -1]);

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_asyncio.AsyncIOMotorCollection.create_index().要使用Motor驱动程序创建索引,请使用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:以下示例在name字段上创建单键降序索引:

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.这个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

collection.createIndex( <key and index type specification>, <options>, <callbackFunction>)

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

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.这个com.mongodb.async.client.MongoCollection.createIndex方法仅在同一规范的索引不存在时创建索引。

To create an index using the .NET driver, use MongoCollection.CreateIndex.要使用.NET驱动程序创建索引,请使用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:以下示例在name字段上创建单键降序索引:

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.这个MongoCollection.CreateIndex方法仅在同一规范的索引不存在时创建索引。

To create an index using the Perl driver, use create_one().要使用Perl驱动程序创建索引,请使用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:以下示例在name字段上创建单键降序索引:

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.create_one()方法仅在同一规范的索引不存在时创建索引。

To create an index using the Ruby driver, use Mongo::Index::View#create_one.要使用Ruby驱动程序创建索引,请使用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:以下示例在name字段上创建单键降序索引:

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.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

collection.createIndex(<key and index type specification>)

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

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.这个org.mongodb.scala.model.Indexes方法仅在同一规范的索引不存在时创建索引。

[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()方法创建名为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 Compound Indexes and Sort on Multiple Fields for more information on compound indexes.有关复合索引的详细信息,请参见复合索引对多个字段排序

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索引

See 2d Index Internals for a high level introduction to geospatial indexes.有关地理空间索引的高级介绍,请参见2d索引内部构件

Text Indexes文本索引

MongoDB provides a text index type that supports searching for string content in a collection.MongoDB提供了一种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.有关文本索引和搜索的详细信息,请参见文本索引

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.这些索引的值沿其范围的分布更为随机,但只支持相等匹配,不支持基于范围的查询。

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.除了unique约束之外,unique索引在功能上可以与其他MongoDB索引互换。

Partial Indexes部分索引

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.部分索引提供了稀疏索引功能的超集,应该优先于稀疏索引。

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索引

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使集合中的数据过期

Hidden Indexes隐藏索引

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索引,您可以隐藏任何索引。

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索引和排序规则

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上有一个索引。

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:以下索引仅支持简单的二进制比较,不支持排序规则

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.有关详细信息,请参阅索引的操作注意事项

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