Three common USES of the MongoDB Remove function

  • 2020-05-10 23:06:31
  • OfStack

In MongoDB, the db.collection.remove () method is used to delete a document from a document. You can delete all documents from one collection, delete all documents that match one condition, or limit the operation to 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 drop the index. Here is an example of deleting all documents from the inventory collection:

db.inventory.remove({})

The drop() method might be more efficient for deleting all documents in a collection, while the drop() method removes the entire collection, including the index, and then recreates the collection and builds the index.

Delete documents that match the conditions:

To delete a document that matches the deletion criteria, you need to call the remove() method and pass one < query > Parameters. The following example removes all documents with type field values of food from the inventory collection:

db.inventory.remove( { type : "food" } )

For large deletions, it might be useful to copy the documents that need to be retained into a new collection and then delete the collection on top of the original collection using the drop() method.

Delete 1 document that matches the conditions:

Delete a document, call remove(), and set the value of the justOne parameter to true or 1. Here is an example of removing a document from the inventory collection where the type field value is food:

db.inventory.remove( { type : "food" }, 1 )

Delete 1 document in a specific order, using the findAndModify() method.


Related articles: