Drop all indexes from all the collections in a MongoDB database using the command line?

To drop all indexes from all collections in a MongoDB database, use the dropIndexes command with the forEach method to iterate through all collections. This operation removes all custom indexes while preserving the mandatory _id index.

Syntax

db.getCollectionNames().forEach(function(collectionName) {
    db.runCommand({dropIndexes: collectionName, index: "*"});
});

Example

Let's first check the current database and view existing indexes before dropping them ?

db
Test

View Current Indexes

Check existing indexes in a collection ?

db.indexingDemo.getIndexes();
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "test.indexingDemo"
    },
    {
        "v" : 2,
        "key" : {
            "StudentFavouriteSubject" : 1
        },
        "name" : "StudentFavouriteSubject_1",
        "ns" : "test.indexingDemo",
        "background" : true
    }
]

Drop All Indexes

Execute the command to drop all indexes from all collections ?

db.getCollectionNames().forEach(function(allCollectionName) {
    db.runCommand({dropIndexes: allCollectionName, index: "*"});
});

Verify Result

Check if indexes were successfully dropped ?

db.indexingDemo.getIndexes();
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "test.indexingDemo"
    }
]

Key Points

  • The * wildcard drops all indexes except the mandatory _id index
  • getCollectionNames() returns an array of all collection names in the current database
  • This operation affects all collections in the database simultaneously

Conclusion

The dropIndexes command with index: "*" efficiently removes all custom indexes from every collection while preserving the required _id index. Use this approach when you need to reset index configurations across an entire database.

Updated on: 2026-03-15T00:27:27+05:30

311 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements