You can remove a specific index from a collection. You may need to drop an index if you see a negative performance impact, want to replace it with a new index, or no longer need the index.您可以从集合中删除特定索引。如果您发现索引对性能有负面影响,想用新索引替换它,或者不再需要该索引,则可能需要删除该索引。
To drop an index, use one of the following shell methods:要删除索引,请使用以下shell方法之一:
db.collection.dropIndex() | |
db.collection.dropIndexes() |
About this Task关于此任务
You can drop any index except the default index on the 您可以删除_id field. To drop the _id index, you must drop the entire collection._id字段上除默认索引之外的任何索引。要删除_id索引,必须删除整个集合。
If you drop an index that's actively used in production, you may experience performance degradation. Before you drop an index, consider hiding the index to evaluate the potential impact of the drop.如果您删除了在生产中积极使用的索引,您可能会遇到性能下降。在删除索引之前,请考虑隐藏索引以评估删除的潜在影响。
Before You Begin开始之前
To drop an index, you need its name. To get all index names for a collection, run the 要删除索引,您需要它的名称。要获取集合的所有索引名称,请运行getIndexes() method:getIndexes()方法:
db.<collection>.getIndexes()Procedures过程
After you identify which indexes to drop, use one of the following drop methods for the specified collection:确定要删除哪些索引后,对指定的集合使用以下删除方法之一:
Drop a Single Index删除单个索引
To drop a specific index, use the 要删除特定索引,请使用dropIndex() method and specify the index name:dropIndex()方法并指定索引名称:
db.<collection>.dropIndex("<indexName>")Drop Multiple Indexes删除多个索引
To drop multiple indexes, use the 要删除多个索引,请使用dropIndexes() method and specify an array of index names:dropIndexes()方法并指定一个索引名称数组:
db.<collection>.dropIndexes( [ "<index1>", "<index2>", "<index3>" ] )Drop All Indexes Except the _id Index删除除_id索引之外的所有索引
_id IndexTo drop all indexes except the 要删除除_id index, use the dropIndexes() method:_id索引之外的所有索引,请使用dropIndexes()方法:
db.<collection>.dropIndexes()Results结果
After you drop an index, the system returns information about the status of the operation.删除索引后,系统将返回有关操作状态的信息。
Example output:示例输出:
...
{ "nIndexesWas" : 3, "ok" : 1 }
...
The value of nIndexesWas reflects the number of indexes before removing an index.nIndexesWas的值反映了删除索引之前的索引数量。
To confirm that the index was dropped, run the 要确认索引已删除,请运行db.collection.getIndexes() method:db.collection.getIndexes()方法:
db.<collection>.getIndexes()
The dropped index no longer appears in the 删除的索引不再出现在getIndexes() output.getIndexes()输出中。
Learn More了解更多
To learn more about managing your existing indexes, see Manage Indexes.要了解有关管理现有索引的更多信息,请参阅管理索引。To learn how to remove an index in MongoDB Compass, see Manage Indexes in Compass.要了解如何在MongoDB Compass中删除索引,请参阅Compass中的管理索引。