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

15,253

Solution 1

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.

Solution 2

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.

Solution 3

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.

Share:
15,253
raffian
Author by

raffian

Applications architect and code slinger since 2000, my background is full stack Java. Reach me at 72616666692e6970616440676d61696c2e636f6d My other passion is landscape photography, check it out if you're interested!

Updated on June 03, 2022

Comments

  • raffian
    raffian about 2 years

    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?