Docs HomeDevelop ApplicationsMongoDB Manual

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. 除了_id字段上的默认索引之外,您可以删除任何索引。To drop the _id index, you must drop the entire collection.要删除_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了解更多信息