In MongoDB, the Db.collection.remove () method is used to delete documents from the document. You can delete all documents from a collection, delete all documents that match one condition, or restrict actions to delete only one document.
Delete all documents:
To delete all documents in the collection, you need to pass an empty query document {} to the Remove () method. The Remove () method does not delete the index. Here is an example of removing all documents from the inventory collection:
Copy Code code as follows:
Delete all documents in the collection, the drop () method may be more efficient, and the drop () method deletes the entire collection, including the index, and then recreate the collection and index.
To delete a document that matches a criterion:
Deleting a document that matches a delete condition requires calling the Remove () method and passing a <query> parameter. The following example deletes all documents of type field value food from the inventory collection:
Copy Code code as follows:
Db.inventory.remove ({type: "Food"})
For large deletions, it is possible to copy the document that needs to be retained into a new collection and then delete the collection using the Drop () method on the original collection.
To delete a document that matches a criterion:
Deletes a document, calls remove (), sets the value of the Justone parameter to TRUE or 1. The following is an example of a document that deletes a Type field value of food from the inventory collection:
Copy Code code as follows:
Db.inventory.remove ({type: "Food"}, 1)
Deletes a document in a specific order using the Findandmodify () method.