Code MongoDB

Dropping a collection without losing the indexes

Long story short, you can’t drop a MongoDB collection without losing the indexes. However, in this post I offer a shell helper that will save the indexes and build them again, so you won’t have to worry about it.

Why not just use remove?

In MongoDB the remove function removes elements oneĀ  by one. So if you have millions of documents, even if you have indexes, it will still take a long time to remove all the documents. If you don’t mind waiting you are welcome to use

It is important to note that this doesn’t lock the database until it is done, it will yield for other operations.

Dropping a collection is risky

If you just drop a collection without saving the indexes, you stand at risk of losing important indexes. If you have rules in place that automatically re-ensureindex a collection, or if you’ve saved all the indexes somewhere, then you’ll be fine.

But what often happens, especially if you’re not careful, is you miss an index or an index key or even an option like unique or sparse.

An alternative solution

If you’re keen on using MongoDB’s shell for administration, I have a shell helper that will allow you to specify a collection to drop. The helper function will also save your indexes and make sure that they are recreated.

It is important to note that dropping a collection will lock the database until it is done. So keep that in mind when doing the drop.

Caveats and improvements

This helperĀ  won’t work as expected for sharded collections or special indexes like text or geographical indexes.

Index options supported so far:

  • sparse
  • unique
  • background

Please feel free to fork the gist.

Thank you for reading this post. Please leave comments if you’ve found this useful or useless.


By Pieter Jordaan

Pieter is a Ph.D student in computer and electronic engineering at the University of the North West. His field of study is a hybrid approach to relational and non-relational databases.

He also enjoys playing the guitar and singing songs. He is married to the beautiful co-author Jeanne-mari Jordaan

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.