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 the 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 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 it.

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

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





MongoDB deleteOne() method

The MongoDB deleteOne() method 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 }

MongoDB deleteMany() method

The MongoDB deleteMany() method 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 }






Read more articles


General Knowledge



Learn Popular Language