MongoDB - Delete - Interview Questions

How do you delete all documents from a collection?

 

MongoDB documents can be deleted using the operation db.collection.deleteMany().

All documents can be deleted from a MongoDB collection by using the operation db.collection.deleteMany() and passing an empty filter {}

For example, below operation deletes all the documents from the employee collection.

>db.employees.deleteMany({})

How do you delete all documents in a collection that match a condition?

 

All documents that match a condition can be deleted from a MongoDB collection by using the operation db.collection.deleteMany() and passing the filter condition { : }

For example, below operation deletes all the documents from the employee collection who has the title 'Manager'.

> db.employees.deleteMany({ title : 'Manager' })

How do you delete a single document in a collection that matches a condition?

 

A single MongoDB document can be deleted using the operation db.collection.deleteOne().

For example, below operation deletes the first document having ‘title’ as ‘manager’.

> db.employees.deleteOne({ title: 'manager'})
 
Important Keywords to Remember

Subscribe to our Questions