MongoDB Delete Document

MongoDB Delete Document – In this MongoDB Tutorial, we shall learn to delete MongoDB Document(s).

To delete documents from MongoDB Collection, follow this step by step guide :

  1. Prepare a Criteria to select those documents for deletion.
    criteria = {field1:value1, field2:value2,..}
  2. [Optional] Query the Documents based on the Criteria formed to cross verify if you want to delete all those selected Documents.
    db.collection.find(criteria)
  3. Use db.collection.remove() method to remove the records based on criteria.
    db.collection.remove(criteria)

Syntax of remove() method

Following is the syntax of remove() method to delete documents from a collection in MongoDB :

where

collection_nameString[mandatory] Name of the Collection from which you would like to remove Documents
CRITERIADocument[optional] The criteria that selects the required documents to delete
JUST_ONE1 or true[optional] If one or true, deletes only one document from the selection

 

Example to Delete Documents based on Criteria

In this example we shall delete only some of the entries of a selection using a criteria. Following is the collection we consider in this example

Now we shall form a criteria,

Check the entries that could be selected using the criteria

There are two entries for this criteria. Once we are sure that we can delete these documents, delete them using remove() method as shown below :

MongoDB acknowledged with result of the Operation, { "nRemoved" : 2 } , saying two documents are deleted.

 

Example to Delete All Documents present in the Collection

In this example, we shall delete all documents present in a collection namedcustomers .

There are four documents in the collection.

To delete all documents in the collection, run db.collection.remove() method with an empty query.

All the documents were deleted from the collection.

 

Example to delete only one Document despite many Documents selected for the criteria

For the following criteria there are two documents.

Now we shall delete only one document using justOne argument of remove() method

Despite multiple Documents for the criteria, only one document is deleted because of the justOne argument. And the rest of the documents continue to exist in the collection.

 

Conclusion :

In this MongoDB Tutorial – MongoDB Delete Document(s), we have learnt to delete one or more documents based on a criteria and also to delete all the documents with examples.