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

MongoDBDatabaseBig Data Analytics

Following is the syntax to drop all indexes from all collections in a MongoDB database using command line

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

The above syntax will drop all indexes except _id.

Let us check the current database. Following is the query

> db

This will produce the following output

Test

Following is the query to let us show some indexes from a collection before dropping indexes

> db.indexingDemo.getIndexes();

This will produce the following output

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

Following is the query to drop all indexes from all the collections in a MongoDB database

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

Following is the query to check whether the indexes have been dropped or not

> db.indexingDemo.getIndexes();

This will produce the following output

[
   {
      "v" : 2,
      "key" : {
         "_id" : 1
      },
      "name" : "_id_",
      "ns" : "test.indexingDemo"
   }
]

Look at the above sample output, indexes have been dropped successfully.

raja
Published on 11-Apr-2019 14:16:55
Advertisements