How to Delete Documents with Condition in MongoDB
In MongoDB, you delete documents that match a condition using
deleteOne() to remove a single matching document or deleteMany() to remove all matching documents. You specify the condition as a filter object inside these methods to target the documents you want to delete.Syntax
The basic syntax to delete documents with a condition uses either deleteOne(filter) or deleteMany(filter). The filter is an object that describes the condition documents must meet to be deleted.
- deleteOne(filter): Deletes the first document that matches the filter.
- deleteMany(filter): Deletes all documents that match the filter.
mongodb
db.collection.deleteOne({ <condition> })
db.collection.deleteMany({ <condition> })Example
This example shows how to delete documents from a users collection where the age is less than 18. It deletes all such documents using deleteMany().
mongodb
db.users.deleteMany({ age: { $lt: 18 } })Output
{ "acknowledged" : true, "deletedCount" : 3 }
Common Pitfalls
Common mistakes include:
- Using
deleteOne()when you want to delete multiple documents, which only deletes one. - Not specifying a filter, which deletes all documents if you use
deleteMany({})unintentionally. - Using incorrect filter syntax, causing no documents to be deleted.
mongodb
/* Wrong: deletes only one document but you want all */ db.users.deleteOne({ age: { $lt: 18 } }) /* Right: deletes all matching documents */ db.users.deleteMany({ age: { $lt: 18 } })
Quick Reference
Use this quick guide to choose the right delete method:
| Method | Description | Deletes |
|---|---|---|
| deleteOne(filter) | Deletes the first document matching the filter | One document |
| deleteMany(filter) | Deletes all documents matching the filter | Multiple documents |
Key Takeaways
Use deleteOne() to remove a single document matching the condition.
Use deleteMany() to remove all documents matching the condition.
Always specify a filter to avoid deleting unintended documents.
Check the deletion result to confirm how many documents were removed.
Incorrect filter syntax can cause no documents to be deleted.