What are the trade-offs of dropping a MongoDB collection vs. removing all of its documents (assuming the collection will be re-created immediately)?
@foreyez The duplicate answer explains what the two options do: drop() completely deletes the collection; remove({}) deletes matching documents while preserving (and updating) indexes. If your intent is to delete a collection, you should use drop() .
To delete all documents in a collection, pass an empty document ( {} ). Optional. To limit the deletion to just one document, set to true . Omit to use the default value of false and delete all documents matching the deletion criteria.
MongoDB's db. collection. drop() is used to drop a collection from the database.
A collection holds one or more BSON documents. Documents are analogous to records or rows in a relational database table. Each document has one or more fields; fields are similar to the columns in a relational database table.
A benefit of simply dropping a collection is that it is much faster than removing all of a collection's documents. If your collection will be "re-created immediately" anyway (assuming that includes index re-creation), then this is probably the most-attractive option.
The authors of the book MongoDB: The Definitive Guide (Kristina Chodorow and Michael Dirolf) ran an experiment where they provided a Python script which timed a drop
vs. a remove
of 1000000 records. The results came in at 0.01 seconds for the drop
and 46.08 seconds for the remove
. Now while the exact times may differ based-on hardware and other factors, it nonetheless illustrates the point that the drop
is significantly faster.
reference: Chodorow K., Dirolf M. (2010). “MongoDB: The Definitive Guide.” O'Reilly Media, Inc. Sebastapol, CA., pp.25
If you go through a remove all the documents from a collection, then you'll be doing a lot more work (freeing the document's storage, clearing the index entries that point to the document, and so on). If you instead just drop the collection, it'll just be reclaiming the extents that the collection and its indexes use.
One other difference is that dropping the collection will also remove the collection's indexes.
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