deleteMany()
deleteMany removes every document that matches the filter.
In this page:
Syntax
db.collection_name.deleteMany(filter)
deleteMany()
Use deleteMany for cleanup such as removing expired sessions. An empty filter deletes all documents but leaves the collection and its indexes, unlike drop. Preview the filter with countDocuments first.
Note:
Run countDocuments with the same filter before deleting.
Example: deleteMany()
test> db.sessions.insertMany([{ _id: 1, expired: true }, { _id: 2, expired: false }, { _id: 3, expired: true }])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3 } }
test> db.sessions.countDocuments({ expired: true })
2
test> db.sessions.deleteMany({ expired: true })
{ acknowledged: true, deletedCount: 2 }
test> db.sessions.find()
[ { _id: 2, expired: false } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Passing {} by accident
- Confusing deleteMany({}) with drop
- Not testing the filter first
Chapter Summary
- deleteMany removes all matches
- {} removes everything but keeps the collection
- Preview with countDocuments
- Returns deletedCount
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: