Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to remove all entries from mongodb

Tags:

mongodb

Which is the better way to remove all entries from a mongodb collection?

db.collection.remove({})

or

db.collection.drop()
like image 804
squal Avatar asked Dec 01 '25 02:12

squal


2 Answers

Remove all documents in a collection

db.collection.remove({}) 

Will only remove all the data in the collection but leave any indexes intact. If new documents are added to the collection they will populate the existing indexes.

Drop collection and all attached indexes

db.collection.drop() 

Will drop the collection and all indexes. If the collection is recreated then the indexes will also need to be re-created.

From your question, if you only want to remove all the entities from a collection then using db.collection.remove({}) would be better as that would keep the Collection intact with all indexes still in place.

From a speed perspective, the drop() command is faster.

like image 153
Kevin Brady Avatar answered Dec 02 '25 19:12

Kevin Brady


db.collection.drop() will delete to whole collection (very fast) and all indexes on the collection.

db.collection.remove({}) will delete all entries but the collection and the indexes will still exists.

So there is a difference in both operations. The first one is faster but it will delete more meta information. If you want to ceep them, you should not use it.

like image 28
Simulant Avatar answered Dec 02 '25 20:12

Simulant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!