Docs 菜单

创建索引

索引支持在 MongoDB 中高效执行查询。如果应用程序在相同字段上重复运行查询,则可以在这些字段上创建索引以提高查询的性能。

如要创建索引,请使用 createIndex() Shell 方法或适用于您的驱动程序的等效方法。本页显示 MongoDB Shell 和驱动程序的示例。

在 MongoDB Shell 或驱动程序中运行创建索引的命令时,MongoDB 仅在没有相同规格索引存在时才创建索引。

尽管索引可提高查询性能,但添加索引会对写入操作的性能产生负面影响。对于具有高写入读取比率的集合,索引的成本很高,因为每次插入和更新还必须更新所有索引。

注意

索引排序顺序

使用降序单字段索引可能会对索引性能产生负面影响。 为获得最佳性能,请仅使用升序单字段索引。


➤ 如要设置此页面上示例的语言,请使用右侧导航窗格中的选择您的语言下拉菜单。


要在 mongosh 中创建索引,请使用 db.collection.createIndex()

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

要使用 .NET 驱动程序 创建索引,请使用 MongoCollection.CreateIndex

collection.CreateIndex( IndexKeys<collection>.<key and index type specification>, <options> );

要使用 Async Java 驱动程序 创建索引,请使用 com.mongodb.async.client.MongoCollection.createIndex

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

要使用 Java 驱动程序创建索引,请使用 com.mongodb.client.MongoCollection.createIndex

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

要使用Motor driver 创建索引,请使用motor.motor_asyncio.AsyncIOMotorCollection.create_index

await db.collection.create_index([(<key and index type specification>)], <options> )

如要使用 Node.JS 驱动程序创建索引,请使用 createIndex()

collection.createIndex( { <key and index type specification> }, function(err, result) {
console.log(result);
callback(result);
} )

要使用 Perl 驱动程序创建索引,请使用 create_one()

my $indexes = $db->get_collection( <collection> )->indexes;
$indexes->create_one( [ <key and index type specification> ] );

如要使用 PHP 驱动程序创建索引,请使用 MongoDB\\Collection::createIndex()

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

要使用 Python 驱动程序创建索引,请使用 pymongo.collection.Collection.create_index方法:

db.collection.create_index([(<key and index type specification>)], <options> )

要使用 Ruby 驱动程序创建索引,请使用 Mongo:: Index:: View #create_one

client[:collection].indexes.create_one({ <key and index type specification> }, {options})

要使用 Scala 驱动程序创建索引,请使用 org.mongodb.scala.model.Indexes

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

此示例在 name 字段上创建一个单键升序索引:

db.collection.createIndex( { name: 1 } )

此示例在 name 字段上创建一个单键升序索引:

collection.CreateIndex( IndexKeys<collection>.Ascending("name") );

此示例在 name 字段上创建一个单键升序索引:

collection.createIndex(Indexes.ascending("name"), someCallbackFunction());

此示例在 name 字段上创建一个单键升序索引:

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

此示例在 name 字段上创建一个单键升序索引:

await collection.create_index([("name", pymongo.ASCENDING)])

此示例在 name 字段上创建一个单键升序索引:

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

此示例在 name 字段上创建一个单键升序索引:

my $indexes = $db->get_collection( <collection> )->indexes;
$indexes->create_one( [ name => 1 ] );

此示例在 name 字段上创建一个单键升序索引:

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

此示例在 name 字段上创建一个单键升序索引:

collection.create_index([("name", pymongo.ASCENDING)])

此示例在 name 字段上创建一个单键升序索引:

client[:collection].indexes.create_one({ name: 1 })

此示例在 name 字段上创建一个单键升序索引:

collection.createIndex(ascending("name"))

您可以使用mongosh来监控索引的创建。

要查看集合中存在哪些索引(包括当前正在构建的索引),请运行 db.collection.getIndexes() 方法:

db.collection.getIndexes()
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { name: -1 }, name: 'name_-1' }
]

要检查您的索引是否正在构建,请使用$currentOp 聚合阶段以返回有关数据库上活动操作的信息。要在$currentOp 中运行mongosh db.aggregate(),请在admin 数据库中使用 方法。

以下聚合管道使用 $match 阶段返回有关在 name 字段上构建降序索引的活动操作的信息:

db.getSiblingDB("admin").aggregate( [
{ $currentOp : {} },
{ $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') }
}, ...
]

要查看有关使用驱动程序创建的现有索引的信息,请参阅驱动程序文档