Delete Document

delete documents from the collections through remove() method. it works like a delete a row from the table in RDBMS.

Syntax:-

> db.collectionName.remove({whereCondition},justOne);

justOne:- (Optional) if set to true or 1, then remove only one document.

In RDBMS:-

delete from tableName where condition=someValue

Example:-

db.employees.remove({name:"Rom"},1)

if the document is deleted then show a message.

WriteResult({ "nRemoved" : 1 })

If you want to remove all documents from the collection then use remove({}) method.

Syntax:-

db.collectionName.remove({});

Example:-

db.employees.remove({})

after delete successfully then show message

WriteResult({ "nRemoved" : NumberOfDocumentsDeleted })

deleteOne():- this method is used to delete one documentfrom the collections.

Syntax:-

db.collectionName.deleteOne({whereCondition})

Example:-

db.employees.deleteOne({name:"Tony"});

Output:-

{ "acknowledged" : true, "deletedCount" : 1 }

deleteMany():- this method is used to delete multiple documents.

Syntax:-

db.collectionName.deleteMany({whereCondition})

Example:-

db.employees.deleteMany({department:"department A"});

Output:-

{ "acknowledged" : true, "deletedCount" : 2 }