MongoDB provides several ways to drop an index or indexes.
To drop a single index, you can use the dropIndex()
method.
To drop multiple indexes, you can use either the dropIndexes()
method or the dropIndexes
administration command.
The dropIndex()
Method
If you only need to drop one index, you can use the dropIndex()
method. This method accepts the index name or its specification document.
Here’s an example of dropping an index using the index name:
db.bars.dropIndex("location_2dsphere")
Output:
{ "nIndexesWas" : 3, "ok" : 1 }
This tells us that the index called location_2dsphere
was dropped successfully.
Here’s an example of dropping an index by passing its specification document:
db.bars.dropIndex( { "name" : 1 } )
Output:
{ "nIndexesWas" : 2, "ok" : 1 }
We can see that this index was also dropped. This index had a specification of { "name" : 1 }
, which is the specification document I used when creating the index.
The dropIndex()
method is a wrapper around the dropIndexes
command.
The dropIndexes()
Method
The dropIndexes()
method can be handy if you need to drop more than one index. You can drop a single index too, it just has the added capability of being able to drop multiple (or all) indexes.
This method accepts the index name or its specification document for each of the indexes to drop. If you’re dropping more than one index, you must provide their names/specification documents in an array.
Here’s an example of dropping two indexes using their index names:
db.pets.dropIndexes( [ "type_1", "name_1" ])
Output:
{ "nIndexesWas" : 3, "ok" : 1 }
Note that, if it’s a text index, you can only specify the index name.
You can drop all indexes (except for the _id
index) by omitting the parameter altogether:
db.pets.dropIndexes()
The dropIndexes()
method is a wrapper around the dropIndexes
command.
The dropIndexes
Command
The dropIndexes
command allows you do do the same thing that the dropIndexes()
method. As mentioned, the dropIndexes()
method is a wrapper around the dropIndexes
command
Here’s an example of dropping a single index:
db.runCommand( { dropIndexes: "posts", index: "title_1" })
Output:
{ "nIndexesWas" : 4, "ok" : 1 }
And here’s an example of dropping multiple indexes:
db.runCommand( {
dropIndexes: "posts",
index: [ "tags_1", "body_text" ]
})
Result:
{ "nIndexesWas" : 3, "ok" : 1 }
To drop all indexes (except for the _id
index), use the asterisk wildcard (*
):
db.runCommand( { dropIndexes: "posts", index: "*" })
Result:
{ "nIndexesWas" : 4, "msg" : "non-_id indexes dropped for collection", "ok" : 1 }