Docs HomeDevelop ApplicationsMongoDB Manual

Create an Index创建索引

Indexes support efficient execution of queries in MongoDB. 索引支持在MongoDB中高效执行查询。If your application is repeatedly running queries on the same fields, you can create an index on those fields to improve performance for those queries.如果应用程序在同一字段上重复运行查询,则可以在这些字段上创建索引,以提高这些查询的性能。

To create an index, use the createIndex() shell method or equivalent method for your driver. 要创建索引,请为驱动程序使用createIndex()shell方法或等效方法。This page shows examples for the MongoDB Shell and drivers.本页显示了MongoDB Shell和驱动程序的示例。

About this Task任务介绍

When you run a create index command in the MongoDB Shell or a driver, MongoDB only creates the index if an index of the same specification does not exist.当您在MongoDB Shell或驱动程序中运行create index命令时,MongoDB仅在不存在相同规范的索引的情况下创建索引。

Although indexes improve query performance, adding an index has negative performance impact for write operations. 尽管索引可以提高查询性能,但添加索引会对写入操作的性能产生负面影响。For collections with a high write-to-read ratio, indexes are expensive because each insert and update must also update any indexes.对于具有高写/读比率的集合,索引是昂贵的,因为每次插入和更新都必须更新任何索引。

Procedure过程


➤ To set the language of the examples on this page, use the Select your language drop-down menu in the right navigation pane.


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);
}

Example实例

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

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

Index Sort Order索引排序顺序

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

Results结果

To confirm that the index was created, use mongosh to run the db.collection.getIndexes() method:要确认索引已创建,请使用mongosh运行db.collection.getIndexes()方法:

db.collection.getIndexes()

Output:输出:

[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { name: -1 }, name: 'name_-1' }
]

To view information on created indexes using a driver, refer to your driver's documentation.要查看有关使用驱动程序创建的索引的信息,请参阅驱动程序文档

Learn More了解更多信息