Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Trade-offs of dropping a collection vs. removing all of its documents

Tags:

What are the trade-offs of dropping a MongoDB collection vs. removing all of its documents (assuming the collection will be re-created immediately)?

like image 292
Matt Avatar asked Aug 27 '12 18:08

Matt


People also ask

What is the difference between dropping a collection and deleting all documents in a collection?

@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() .

How do I remove all records from a collection in MongoDB?

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.

What is the fastest operation to clear an entire collection in MongoDB?

MongoDB's db. collection. drop() is used to drop a collection from the database.

What is difference between collection and documents in MongoDB?

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.


2 Answers

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

like image 80
Aaron Avatar answered Oct 20 '22 13:10

Aaron


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.

like image 40
Louisa Avatar answered Oct 20 '22 12:10

Louisa