Indexes support efficient execution of queries in 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.索引支持在MongoDB中高效执行查询。如果应用程序在相同的字段上重复运行查询,您可以在这些字段上创建索引,以提高这些查询的性能。
To create an index, use the 要创建索引,请使用createIndex() shell method or equivalent method for your driver. This page shows examples for the MongoDB Shell and drivers.createIndex()shell方法或驱动程序的等效方法。此页面显示了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.要设置此页面上示例的语言,请使用右侧导航窗格中的“选择语言”下拉菜单。
MongoDB Shell
To create an index in 要在mongosh, use db.collection.createIndex().mongosh中创建索引,请使用db.collection.createIndex()。
db.collection.createIndex( <key and index type specification>, <options> )C#
To create an index using the .NET driver, use MongoCollection.CreateIndex.要使用.NET驱动程序创建索引,请使用MongoCollection.CreateIndex。
collection.CreateIndex( IndexKeys<collection>.<key and index type specification>, <options> );Java(Async)
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>)Java(Sync)
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>)Kotlin(Coroutine)
To create an index by using the Kotlin Coroutine Driver, use the 要使用Kotlin协程驱动程序创建索引,请使用MongoCollection.createIndex() method.MongoCollection.createIndex()方法。
collection.createIndex(<key and index type specification>, <options>)Motor
To create an index using the Motor driver, use 要使用Motor驱动程序创建索引,请使用motor.motor_asyncio.AsyncIOMotorCollection.create_index.motor.motor_asyncio.AsyncIOMotorCollection.create_index。
await db.collection.create_index([(<key and index type specification>)], <options> )Node.js
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);
} )Perl
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> ] );PHP
To create an index using the PHP driver, use 要使用PHP驱动程序创建索引,请使用MongoDB\\Collection::createIndex().MongoDB\\Collection::createIndex()。
$collection->createIndex(<key and index type specification>, <options>);Python
To create an index using the Python driver, use the pymongo.collection.Collection.create_index method:要使用Python驱动程序创建索引,请使用pymongo.collection.Collection.create_index方法:
db.collection.create_index([(<key and index type specification>)], <options> )Ruby
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})scala
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>)Example示例
MongoDB Shell
This example creates a single key ascending index on the 此示例在name field:name字段上创建了一个单键升序索引:
db.collection.createIndex( { name: 1 } )C#
This example creates a single key ascending index on the 此示例在name field:name字段上创建了一个单键升序索引:
collection.CreateIndex( IndexKeys<collection>.Ascending("name") );Java(Async)
This example creates a single key ascending index on the 此示例在name field:name字段上创建了一个单键升序索引:
collection.createIndex(Indexes.ascending("name"), someCallbackFunction());Java(Sync)
This example creates a single key ascending index on the 此示例在name field:name字段上创建了一个单键升序索引:
collection.createIndex(Indexes.ascending("name"));Kotlin(Coroutine)
This example creates a single key ascending index on the 此示例在name field:name字段上创建了一个单键升序索引:
collection.createIndex(Indexes.descending("name"))Motor
This example creates a single key ascending index on the 此示例在name field:name字段上创建了一个单键升序索引:
await collection.create_index([("name", pymongo.ASCENDING)])Node.js
This example creates a single key ascending index on the 此示例在name field:name字段上创建了一个单键升序索引:
collection.createIndex( { name : 1 }, function(err, result) {
console.log(result);
callback(result);
} )Perl
This example creates a single key ascending index on the 此示例在name field:name字段上创建了一个单键升序索引:
my $indexes = $db->get_collection( <collection> )->indexes;
$indexes->create_one( [ name => 1 ] );PHP
This example creates a single key ascending index on the 此示例在name field:name字段上创建了一个单键升序索引:
$collection->createIndex(['name' => 1]);Python
This example creates a single key ascending index on the 此示例在name field:name字段上创建了一个单键升序索引:
collection.create_index([("name", pymongo.ASCENDING)])Ruby
This example creates a single key ascending index on the 此示例在name field:name字段上创建了一个单键升序索引:
client[:collection].indexes.create_one({ name: 1 })scala
This example creates a single key ascending index on the 此示例在name field:name字段上创建了一个单键升序索引:
collection.createIndex(ascending("name"))Results结果
You can use 您可以使用mongosh to monitor the creation of your index.mongosh来监视索引的创建。
To see what indexes exist on your collection, including indexes that are currently being built, run the 要查看集合上存在哪些索引,包括当前正在构建的索引,请运行db.collection.getIndexes() method:db.collection.getIndexes()方法:
db.collection.getIndexes()
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { name: -1 }, name: 'name_-1' }
]
To check if your index is being built, use the 要检查是否正在构建索引,请使用$currentOp aggregation stage to return information about active operations on your database. $currentOp聚合阶段返回有关数据库上活动操作的信息。To run 要在$currentOp in mongosh, use the db.aggregate() method on the admin database.mongosh中运行$currentOp,请在admin数据库上使用db.aggregate()方法。
The following aggregation pipeline uses the 以下聚合管道使用$match stage to return information about an active operation that builds a descending index on the name field:$match阶段返回有关在名称字段上构建降序索引的活动操作的信息:
db.getSiblingDB("admin").aggregate( [
{ $currentOp : { idleConnections: true } },
{ $match : {"command.createIndexes": { $exists: true } } }
] )
[
{
type: 'op',
host: 'mongodb.example.net:27017',
desc: 'conn584',
connectionId: 584,
client: '104.30.134.189:12077',
appName: 'mongosh 2.3.4',
clientMetadata: {
...
},
active: true,
currentOpTime: '2024-12-05T16:13:35.571+00:00',
effectiveUsers: [ { user: jane-doe, db: 'admin' } ],
isFromUserConnection: true,
threaded: true,
opid: ...,
lsid: {
...
},
secs_running: Long('3'),
microsecs_running: Long('3920881'),
op: 'command',
ns: 'example_db.collection',
redacted: false,
command: {
createIndexes: 'collection',
indexes: [ { name: 'name_-1', key: { name: -1 } } ],
apiVersion: '1',
lsid: { id: UUID('570931be-c692-4963-b9e2-1e279efd9702') },
'$clusterTime': {
clusterTime: Timestamp({ t: 1733415063, i: 32 }),
signature: {
hash: Binary.createFromBase64('z0zaUHJ5SfhNQyvQLhocsKRFNbo=', 0),
keyId: Long('7444956895695077380')
}
},
'$db': 'example_db'
},
numYields: 0,
queues: {
...
},
currentQueue: null,
locks: {},
waitingForLock: false,
lockStats: { ... },
waitingForFlowControl: false,
flowControlStats: { acquireCount: Long('3') }
}, ...
]
MongoDB marks index builds in various stages, including waiting on commit quorum, as an idle connection by setting the MongoDB通过将active field to false. The idleConnections: true setting includes these idle connections in the $currentOp output.active字段设置为false,将各个阶段的索引构建(包括等待提交仲裁)标记为空闲连接。idleConnections: true设置在$currentOp输出中包括这些空闲连接。
To view information on existing 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如何构建索引,请参阅索引构建过程。