Docs Home → Develop Applications → MongoDB Manual
Create an Index创建索引
On this page本页内容
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 要使用Node.JS驱动程序创建索引,请使用createIndex().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);
}
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了解更多信息
To learn how to create indexes in MongoDB Compass, see Manage Indexes in the Compass documentation.要了解如何在MongoDB Compass中创建索引,请参阅Compass文档中的管理索引。To see how often your indexes are used, see Measure Index Use.要查看索引的使用频率,请参阅度量索引的使用。To learn how to specify the name of your index, see Specify an Index Name.要了解如何指定索引的名称,请参阅指定索引名称。To learn how MongoDB builds indexes, see Index Build Process.要了解MongoDB如何构建索引,请参阅索引构建过程。