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

后端 未结 4 1128
旧巷少年郎
旧巷少年郎 2020-12-29 05:42

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

4条回答
  •  忘掉有多难
    2020-12-29 05:49

    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.

提交回复
热议问题