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.
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:-
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:-
remove({}) method
this method is used to delete all documents from the collection.
Syntax:-
db.collectionName.remove({});
after delete successfully then show message
Example:-
db.employees.remove({})
MongoDB Delete Document – Interview Questions
Q 1: How do you delete a single document?
Ans: Use deleteOne().
Q 2: How do you delete multiple documents?
Ans: Use deleteMany().
Q 3: Can you delete all documents in the collection?
Ans: Yes using deleteMany({}).
Q 4: Does delete remove the collection?
Ans: No, only documents.
Q 5: Is deletion permanent?
Ans: Yes