MongoDB Delete Document

There are multiple methods in MongoDB to delete the documents from the collections like remove(), deleteOne(), deleteMany() methods. 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:-
Suppose, you have employees collection


[
	{
	"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
	"name" : "John",
	"age" : 35,
        "department":"department A"
	},
	{
	"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
	"name" : "Rom",
	"age" : 31,
        "department":"department A"
	},
	{
	"_id" : ObjectId("5fdcdb87b6dad382104b0f87"),
	"name" : "Mathew",
	"age" : 32,
        "department":"department A"
	}
]

Now, you want to delete document where name is Rom


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

if the document is deleted then show a message.

WriteResult({ “nRemoved” : 1 })

deleteOne() method

this method is used to delete one document from the collection.

Syntax:-


db.collectionName.deleteOne({whereCondition})

Example:-


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

Output:-

{ “acknowledged” : true, “deletedCount” : 1 }

deleteMany() method

this method is used to delete multiple documents from the collection.

Syntax:-


db.collectionName.deleteMany({whereCondition})

Example:-


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

Output:-

{ “acknowledged” : true, “deletedCount” : 3 }

remove({}) method

this method is used to delete all documents from the collection.

Syntax:-


db.collectionName.remove({});

after delete successfully then show message

WriteResult({ “nRemoved” : NumberOfDocumentsDeleted })

Example:-


db.employees.remove({})