In this post, we will explore how to use the dropIndexes() method in MongoDB Shell to remove an index from a given collection. We will also build a simple script to remove all the indexes from a given collection.
Let’s dive in.
MongoDB Db.Collection.DropIndexes()
To drop a specific index from a collection, we use the dropIndexes() method and pass the target index that you wish to remove from the collection.
You can specify the index name if it’s a text index or the index specification document otherwise.
Example 1: Drop an Index by Name
In the following example query, we can use the dropIndexes() method to drop an index under the name, “type”.
The given command removes the index with the name, “type”. Dropping an index by name is supported for text index types.
The query returns an output as follows:
Example 2: Drop Multiple Indexes by Name
We can also remove multiple indexes using their names as shown in the following example query:
In this case, the command should remove the “year” and “rating” indexes from the collection.
Output:
Example 3: Drop All Indexes Except the _id Index
The following example query shows how to use the dropIndexes() method to drop all the indexes from a given collection except the _id index.
The command should remove all the non _id indexes from the collection as shown in the following output:
nIndexesWas: 4,
msg: 'non-_id indexes dropped for collection',
ok: 1
}
Example 4: Drop All Indexes from a Given Database
If we wish to remove all the indexes from a given database, we can use a simple script as shown in the following example:
... db.runCommand({dropIndexes: collectionName, index: "*"});
... });
The previous command uses the forEach function to iterate over each collection in the database. It then passes each collection to the dropIndexes command and the target index as a wildcard character.
This should allow you to remove all the non _id indexes from the database in a simple step.
Conclusion
In this post, we discussed how to use the dropIndexes method in the MongoDB Shell to remove one or multiple indexes from a collection.