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

raffian picture raffian · Dec 14, 2011 · Viewed 13.2k times · Source

If I create a collection in Mongo, and after adding documents to this collection I use ensureIndex() to create an index on, say, a number field on a document in this collections, if I drop the collection, do I have to recreate the index?

Answer

lig picture lig · Dec 14, 2011

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.