
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Drop All Indexes from All Collections in a MongoDB Database
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.
Advertisements