Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Drop and Remove in Mongodb? [duplicate]

Tags:

mongodb

I see there's two ways to remove collections in Mongodb. I just want to delete it essentially.

Should I use:

db.collection.drop()

Or

db.collection.remove()
like image 698
Shai UI Avatar asked Mar 10 '17 19:03

Shai UI


1 Answers

Once we have documents stored in our collection , we can remove all of the documents from it in two ways. Now choosing one over another is totally depends on your requirement.

1. Using drop(): By invoking drop() on a collection , it will remove all the documents from it ,it will delete all the indexes on it and at the end it will delete the collection itself.

2.Using remove(): remove has two overloaded versions ,one in which we will pass the criteria to remove all the documents that are matching our passed criteria and 2nd one is default where we won’t pass any criteria (prior to 2.6) or pass an empty document (version 2.6 or more) and it will remove all the documents from the collection. Here, we are more interested in 2nd version when our intention is to clear all the documents from a collection.

Remark: To remove all documents from a collection, it may be more efficient to use the drop() method to drop the entire collection, including the indexes, and then recreate the collection and rebuild the indexes.

like image 92
Ruhul Amin Avatar answered Oct 23 '22 02:10

Ruhul Amin