Database Manual / Indexes

Drop an Index删除索引

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方法之一:

Method方法Description描述
db.collection.dropIndex()Drops a specific index from the collection.从集合中删除特定索引。
db.collection.dropIndexes()Drops all removable indexes from the collection or an array of indexes, if specified.从集合或索引数组中删除所有可移动索引(如果指定)。

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索引之外的所有索引

To 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了解更多