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?
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.
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.
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.
Yes, to all.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With