In MongoDB, if collection is dropped, indexes dropped automatically as well? In MongoDB, if collection is dropped, indexes dropped automatically as well? mongodb mongodb

In MongoDB, if collection is dropped, indexes dropped automatically as well?


Short answer: yes.

Indexes are dropping on collection drop. You need to recreate an index.

You may want to not to drop collection but remove all items in it with db.collection_name.remove({}). It will take more resources but leave your indexes. Actually it will need to delete all index data. That is why it is more preferred to drop the whole collection and recreate indexes after that.


I just did this on a collection with 10 indexes and didn't want to manually recreate those. You can accomplish a drop and recreate with indexes with the following three lines in the mongo shell:

var indexes = db.collection.getIndexKeys().splice(1)db.collection.drop();indexes.forEach(function(el){ db.collection.ensureIndex(el, {background:true}); })

This isn't smart enough to handle unique or sparse indexes but I think that would be fairly easy to support by using the output of getIndexes() instead. I didn't need that, so I didn't do it.

The splice(1) is just to remove the index on _id, since that will be auto created.


Dropping a collection does drop all the indexes, as you suspect, so when you recreate the collection (either explicitly, or implicitly by adding new documents) you will need to recreate any indexes you need to have present. The default index on _id is created for you automatically.