Drop all indexes from all collections in a MongoDB database using the command line
Asked Answered
S

2

25

I've used mongorestore to restore a database but I'm getting an error that the index already exists when I try to run my application.

I know of the function db.collection.dropIndex() but is there a way to automate this and drop all indexes from all collections in a database at once?

I've tried

db.getCollectionNames().forEach(function(col_name) {   
   var coll = db.getCollection(col_name);   
   coll.dropIndexes(); 
});

But that doesn't do the trick. Any ideas?

Seleucid answered 16/6, 2014 at 10:35 Comment(2)
Then go with db.dropDatabase; command if you want to start with fresh database...!!!Ancestor
This happened to me with my Spring application. If you're using Spring, you might try upgrading your MongoDB drivers. I think the newer drivers address this, but I'm not positive since I used the below solution to destroy, and re-create, all my indexes. If I had more time, and wasn't like "Ohhhh no! Production is down!" I'd have tried upgrading my MongoDB drivers in a controlled, testing, environment, first.Paulapauldron
I
43

Your command works for me (it drops all indexes on the currently selected DB). You can also use this alternative.

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

When dropping indexes only non _id indexes will be dropped.

Workaround solution is to drop the database and set --noIndexRestore flag when restoring with mongorestore so that the indexes are not restored.

From man mongorestore:

--noIndexRestore

New in version 2.2.

Prevents mongorestore from restoring and building indexes as specified in the corresponding mongodump output.

Intelligibility answered 16/6, 2014 at 11:0 Comment(0)
M
5

You can use this command to drop all the indexes from all the collections:

db.getCollectionNames().forEach(function (d) {
   db[d].dropIndexes();
});

Try this!

Reference link

Marinamarinade answered 31/5, 2017 at 11:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.