Indexes

在本页面

索引支持在 MongoDB 中高效执行查询。没有索引,MongoDB 必须执行集合扫描,即扫描集合中的每个文档,以选择与查询语句匹配的那些文档。如果查询存在适当的索引,则 MongoDB 可以使用该索引来限制它必须检查的文档数。

索引是特殊的数据结构[1],它们以易于遍历的形式存储集合数据集的一小部分。索引存储一个特定字段或一组字段的值,按该字段的值排序。索引条目的排序支持有效的相等匹配和基于范围的查询操作。另外,MongoDB 可以通过使用索引中的 Sequences 返回排序的结果。

下图说明了使用索引选择和排序匹配文档的查询:

使用索引选择并返回排序结果的查询图。索引按升序存储“分数”值。 MongoDB 可以按升序或降序遍历索引以返回排序的结果。

从根本上说,MongoDB 中的索引类似于其他数据库系统中的索引。 MongoDB 在collection级别定义索引,并支持 MongoDB 集合中文档的任何字段或子字段的索引。

默认_id 索引

在创建集合期间,MongoDB 在_id字段上创建一个unique index_id索引可防止 Client 端为_id字段插入两个具有相同值的文档。您不能将此索引放在_id字段上。

Note

sharded clusters中,如果_id字段用作shard key,则您的应用程序必须**确保_id字段中值的唯一性以防止错误。这通常是通过使用标准的自动生成的ObjectId完成的。

创建索引

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala

To create an index in the Mongo Shell, use 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:

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.

Important

To create an index on a collection in MongoDB Compass, the collection must contain documents.

To create an index in MongoDB Compass, complete the following steps:

  • Navigate to the collection for which you wish to create the index:

  • In the left-hand MongoDB Compass navigation pane, click the database to which your target collection belongs.

    • From the database view, click the target collection name.
  • Click the Indexes tab:

Compass index tab

  • Click the Create Index button:

Compass index button

The following dialog appears:

  • (Optional) Enter the index name.

Leaving this field blank causes MongoDB Compass to create a default name for the index.

  • Add fields to the index.

Use the Configure the index definition section of the dialog to define the fields for your index and their respective types. To create an index on multiple fields, click Add another field.

  • (Optional) Specify the index options.

The following index options can be specified:

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 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 Node.JS driver, use 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:

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.

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 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 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 .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 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 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]MongoDB 索引使用 B 树数据结构。

Index Types

MongoDB 提供了许多不同的索引类型来支持特定类型的数据和查询。

Single Field

除 MongoDB 定义的_id索引外,MongoDB 还支持在文件的单一栏位上创建用户定义的升/降索引。

``分数''字段上的索引图(升序)。

对于单字段索引和排序操作,索引键的排序 Sequences(即升序或降序)无关紧要,因为 MongoDB 可以沿任一方向遍历索引。

有关单字段索引的更多信息,请参见单字段索引用单个字段索引排序

Compound Index

MongoDB 还支持多个字段(即compound indexes)上的用户定义的索引。

复合索引中列出的字段 Sequences 具有重要意义。例如,如果一个复合索引由{ userid: 1, score: -1 }组成,则索引首先按userid排序,然后在每个userid值内按score排序。

在 userid 字段(升序)和 score 字段(降序)上的复合索引图。索引首先按 userid 字段排序,然后按 score 字段排序。

对于复合索引和排序操作,索引键的排序 Sequences(即升序或降序)可以确定索引是否可以支持排序操作。有关索引 Sequences 对复合索引结果的影响的更多信息,请参见Sort Order

有关复合索引的更多信息,请参见Compound Indexes在多个字段上排序

Multikey Index

MongoDB 使用multikey indexes来索引存储在数组中的内容。如果您对保存数组值的字段构建索引,则 MongoDB 会为数组的“每个”元素创建单独的索引条目。这些multikey indexes允许查询通过匹配数组的一个或多个元素来选择包含数组的文档。如果索引字段包含数组值,MongoDB 会自动确定是否创建多键索引。您无需显式指定多键类型。

addr.zip 字段上的多键索引图。 addr 字段包含地址文档的数组。地址文档包含``zip''字段。

有关多键索引的更多信息,请参见Multikey Indexes多键索引范围

Geospatial Index

为了支持对地理空间坐标数据的有效查询,MongoDB 提供了两个特殊的索引:2d indexes返回结果时使用平面几何,而2dsphere indexes使用球面几何返回结果。

有关地理空间索引的高级介绍,请参见2 d 索引内部

Text Indexes

MongoDB 提供了一种text索引类型,该类型支持在集合中搜索字符串内容。这些文本索引不存储特定于语言的* stop 词(例如“ the”,“ a”,“ or”)和 stem *集合中的词,仅存储根词。

有关文本索引和搜索的更多信息,请参见Text Indexes

Hashed Indexes

为了支持基于哈希的分片,MongoDB 提供了hashed index类型,该类型索引字段值的哈希值。这些索引在其范围内具有更随机的值分布,但是支持相等匹配,而不能支持基于范围的查询。

Index Properties

Unique Indexes

索引的unique属性使 MongoDB 拒绝索引字段的重复值。除了唯一约束之外,唯一索引在功能上可以与其他 MongoDB 索引互换。

Partial Indexes

3.2 版中的新功能。

Partial indexes仅索引集合中符合指定过滤器表达式的文档。通过索引集合中文档的子集,部分索引具有较低的存储需求,并降低了索引创建和维护的性能成本。

部分索引提供了稀疏索引功能的超集,应优先于稀疏索引。

Sparse Indexes

索引的sparse属性可确保索引仅包含具有已索引字段的文档的条目。索引会跳过没有具有索引字段的文档。

您可以将稀疏索引选项与唯一索引选项结合使用,以拒绝具有重复值的文档,而忽略没有索引键的文档。

TTL Indexes

TTL indexes是特殊索引,MongoDB 可以使用它们在一定时间后自动从集合中删除文档。对于某些类型的信息(例如机器生成的事件数据,日志和会话信息),它们仅需要在数据库中保留有限的时间,这是理想的选择。

有关实现的说明,请参见:通过设置 TTL 使集合中的数据过期

Index Use

索引可以提高读取操作的效率。 分析查询性能教程提供了带有和不带有索引的查询的执行统计信息的示例。

有关 MongoDB 如何选择要使用的索引的信息,请参阅query optimizer

索引和整理

3.4 版的新功能。

Collation允许用户为字符串比较指定特定于语言的规则,例如字母大写和重音符号的规则。

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala

Important

MongoDB Compass does not support collation for indexes.

The following examples illustrate indexes and collation in the Mongo Shell.

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.

要将索引用于字符串比较,操作还必须指定相同的排序规则。也就是说,如果排序规则的索引指定了不同的排序规则,则该索引不能支持对索引字段执行字符串比较的操作。

例如,集合myColl在具有排序规则语言环境"fr"的字符串字段category上具有索引。

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

以下查询操作指定与索引相同的排序规则,可以使用索引:

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

但是,默认情况下使用“简单”二进制整理程序的以下查询操作不能使用索引:

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

对于索引前缀键不是字符串,数组和嵌入式文档的复合索引,指定其他排序规则的操作仍可以使用索引来支持索引前缀键的比较。

例如,集合myColl在数字字段scoreprice和字符串字段category上具有复合索引;使用排序规则语言环境"fr"创建索引以进行字符串比较:

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

以下使用"simple"二进制排序规则进行字符串比较的操作可以使用索引:

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

以下操作将"simple"二进制排序规则用于在已索引的category字段上进行字符串比较,可以使用该索引来仅满足查询的score: 5部分:

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

有关整理的更多信息,请参见整理参考页

以下索引仅支持简单的二进制比较,不支持collation

Covered Queries

当查询条件和查询的projection仅包含索引字段时,MongoDB 将直接从索引返回结果,而无需扫描任何文档或将文档放入内存。这些涵盖的查询可能非常有效。

仅使用索引来匹配查询条件并返回结果的查询图。 MongoDB 无需检查索引之外的数据即可完成查询。

有关涵盖查询的更多信息,请参见Covered Query

Index Intersection

2.6 版的新功能。

MongoDB 可以使用索引的交集来执行查询。对于指定复合查询条件的查询,如果一个索引可以满足查询条件的一部分,而另一个索引可以满足查询条件的另一部分,则 MongoDB 可以使用两个索引的交集来满足查询。使用复合索引还是使用索引交集是否更有效取决于特定的查询和系统。

有关索引交点的详细信息,请参见Index Intersection

Restrictions

某些限制适用于索引,例如索引键的长度或每个集合的索引数。有关详情,请参见Index Limitations

Additional Considerations

尽管索引可以提高查询性能,但是索引还提出了一些操作上的考虑。有关更多信息,请参见索引的操作注意事项

如果您的集合包含大量数据,并且您的应用程序需要能够在构建索引的同时访问数据,请考虑在后台构建索引,如Background Construction中所述。

有关索引构建过程的更多信息,请参见填充集合上的索引构建操作,包括在副本集和分片群集上构建索引部分。

一些驱动程序可能使用NumberLong(1)而不是1作为规范来指定索引。这对结果索引没有任何影响。