Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 956
raffian Avatar asked Dec 14 '11 14:12

raffian


People also ask

Does MongoDB automatically index?

MongoDB automatically determines whether to create a multikey index if the indexed field contains an array value; you do not need to explicitly specify the multikey type.

How do I drop all indexes in MongoDB?

To drop all indexes except the _id index and the last remaining shard key index from the collection if one exists, specify "*" . To drop a single index, specify either the index name, the index specification document (unless the index is a text index), or an array of the index name.

Which of the following commands drop all indexes on a collection and recreate them in MongoDB?

Starting in MongoDB 5.2, you can use db. collection. dropIndexes() to drop existing indexes on the same collection even if there is a build in progress on another index.

Does removing all collections in a database also remove the database in MongoDB?

Yes, to all.


2 Answers

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.

like image 192
lig Avatar answered Oct 02 '22 17:10

lig


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.

like image 28
shadfc Avatar answered Oct 02 '22 17:10

shadfc