MongoDB

MongoDB Remove All Indexes from the Database

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”.

ent> db.netflix.dropIndexes("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:

{ nIndexesWas: 4, ok: 1 }

Example 2: Drop Multiple Indexes by Name

We can also remove multiple indexes using their names as shown in the following example query:

db.netflix.dropIndexes("year", "rating")

In this case, the command should remove the “year” and “rating” indexes from the collection.

Output:

{ nIndexesWas: 3, ok: 1 }

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.

db.netflix.dropIndexes()

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.getCollectionNames().forEach(function(collectionName) {
... 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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list