MongoDB Delete Document

The remove() method of MongoDb is used to delete the existing document or documents from a collection.

Syntax

 
db.collection.remove(query, justOne)
 

query - It is an optional parameter and specify delete criteria.
justOne - It is also an optional parameter and of type boolean, if it is set to true or 1, then it removes only one document.

If no any parameter is given to remove() operation, it will clear all documents of a collection. This method does not actually delete a collection, it only removes documents from a collection. If you want to delete a collection along with its all indexes, use the drop() method.

Example of delete document

 
db.students.remove({'name': 'Andy Joya'})
 

The above operation deletes documents having name 'Andy Joya'. Once data has been deleted, we cannot recover them.

The remove method cannot delete document from capped collection. To remove from the capped collection, use drop() method.

Instead of remove, there are two more methods to delete documents.





deleteOne()

It removes a single document from a collection that matches the specified criteria.

Syntax

 
db.collection.deleteOne(<filter>)
 

Here, the filter is of document type and specifies deletion criteria.

Example of deleteOne()

The following operation deletes the students first matching document with age '10'.

> db.students.deleteOne({"age": 10});
{ "acknowledged" : true, "deletedCount" : 1 }

deleteMany()

It removes all documents from a collection that matches the criteria.

Syntax

 
db.collection.deleteMany(<filter>)
 

Here, the filter is of document type and specifies deletion criteria.

Example of deleteMany()

The following operation deletes the students all matching documents with age '11'.

> db.students.deleteMany({"age": 11});
{ "acknowledged" : true, "deletedCount" : 2 }