← Back to MongoDB Course | Chapter 5: CRUD — Delete | Lesson 2 of 6

deleteMany()

deleteMany removes every document that matches the filter.

In this page:

  1. deleteMany()
Syntax
javascript
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()

bash
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
  1. Passing {} by accident
  2. Confusing deleteMany({}) with drop
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.