Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 474
Simon Avatar asked Jun 16 '14 10:06

Simon


People also ask

How do I drop all indexes in MongoDB?

To drop all indexes except the _id index and the last remaining shard key index from the collection if one exists, specify "*" . To drop a single index, specify either the index name, the index specification document (unless the index is a text index), or an array of the index name.

Which of the following commands drop all indexes on a collection and recreate them in MongoDB?

Starting in MongoDB 5.2, you can use db. collection. dropIndexes() to drop existing indexes on the same collection even if there is a build in progress on another index.

Which of the following command is used to get all the indexes of a collection?

You can find all the available indexes in a MongoDB collection by using the getIndexes method. This will return all the indexes in a specific collection. Result: The output contains the default _id index and the user-created index student name index.

What is the command to drop collection in MongoDB?

MongoDB's db. collection. drop() is used to drop a collection from the database.


2 Answers

Your command works for me (it drops all indexes on the currently selected DB). But 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.

like image 93
Christian P Avatar answered Sep 18 '22 14:09

Christian P


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

like image 37
Rahul Mankar Avatar answered Sep 21 '22 14:09

Rahul Mankar