对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

db. 集合.dropIndex()(mongosh方法)

db.collection.dropIndex(index)

带驱动程序的 MongoDB

此页面记录了mongosh方法。要查看MongoDB驾驶员中的等效方法,请参阅您的编程语言的相应页面:

从集合中删除或移除指定索引。

注意

To get the index name or the index specification document for the db.collection.dropIndex() method, use the db.collection.getIndexes() method.

The db.collection.dropIndex() method takes the following parameter:

Parameter
类型
说明

index

字符串或文档

必需。指定要删除的索引。可以通过索引名称或索引规范文档来指定索引。

要删除文本索引,请指定该索引的名称。

您无法指定 "*" 来删除所有非 _id 索引。请改用 db.collection.dropIndexes()

If an index specified to db.collection.dropIndex() is still building, db.collection.dropIndex() attempts to stop the in-progress build. Stopping an index build has the same effect as dropping the built index. See Stop In-Progress Index Builds for more complete documentation.

此方法可用于以下环境中托管的部署:

  • MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务

注意

所有 MongoDB Atlas 集群都支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令

从MongoDB5.2 开始,即使正在构建另一个索引,也可以使用db.collection.dropIndex() 删除同一集合上的现有索引。在早期版本中,在索引构建期间尝试删除其他索引会导致BackgroundOperationInProgressForNamespace 错误。

db.collection.dropIndex() obtains an exclusive lock on the specified collection for the duration of the operation. All subsequent operations on the collection must wait until db.collection.dropIndex() releases the lock.

If an index specified to db.collection.dropIndex() is still building, db.collection.dropIndex() attempts to stop the in-progress build. Stopping an index build has the same effect as dropping the built index.

For replica sets, run db.collection.dropIndex() on the primary. The primary stops the index build and creates an associated "abortIndexBuild" oplog entry. Secondaries which replicate the "abortIndexBuild" oplog entry stop the in-progress index build and discard the build job. See Index Build Process for detailed documentation on the index build process.

使用 currentOp 确定与 createIndexesdb.collection.createIndexes() 操作相关的索引构建。有关示例,请参阅主动索引操作

MongoDB 提供对查询规划器隐藏或取消隐藏索引的功能。通过向规划器隐藏索引,您可以评估在不实际删除索引的情况下删除索引的潜在影响。

如果经过评估后,用户决定删除该索引,则您可以删除隐藏索引;即不需要先取消隐藏才能删除。

如有不利影响,用户可以取消隐藏索引,而不必重新创建已删除的索引。由于索引在隐藏期间得到完全维护,因此一旦取消隐藏,索引就立即可用。

有关隐藏索引的更多信息,请参阅隐藏索引

pets集合中,对 cat字段创建降序索引:

db.pets.createIndex( { cat: -1 }, { name: "catIdx" } )

要查看 pets 集合中的索引,运行 getIndexes() 方法:

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

字段cat 上的单字段索引的用户指定名称为 catIdx,索引规范文档为 { "cat" : -1 }

要删除索引 catIdx,您可以使用索引名称:

db.pets.dropIndex( "catIdx" )

或者,也可以使用索引规范文档 { "cat" : -1 }

db.pets.dropIndex( { "cat" : -1 } )

dropIndex 命令返回运行命令之前集合中的索引数,并指示命令是否成功:

{ nIndexesWas: 2, ok: 1 }

要确认索引已删除,请再次运行getIndexes() 方法:

db.pets.getIndexes()
[ { v: 2, key: { _id: 1 }, name: '_id_' } ]
给本页内容打分