squal
squal

Reputation: 60

Efficient way to remove all entries from mongodb

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

db.collection.remove({})

or

db.collection.drop()

Upvotes: 3

Views: 4791

Answers (2)

Kevin Brady
Kevin Brady

Reputation: 1724

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.

Upvotes: 4

Simulant
Simulant

Reputation: 20132

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.

Upvotes: 2

Related Questions