Deleting Documents and bulkWrite
Deleting is the one operation you cannot take back with another query. A missing filter or a typo can empty a collection in a millisecond. This lesson pairs deletes with bulkWrite, the tool for sending many changes at once, because both reward the same habit: look before you act.
The rule
Delete with the filter you have already read; batch many writes in one bulkWrite.
db.books.deleteOne({ _id: 2 }) // { acknowledged: true, deletedCount: 1 }
db.books.deleteMany({ stock: 0 }) // every out-of-stock book
db.books.deleteMany({}) // ALL documents; collection and indexes stay
db.books.drop() // the collection itself, indexes included- deleteOne removes the first match; use it with a unique filter such as
_id. With a loose filter like{ genres: "classic" }you cannot be sure which of three books goes. - deleteMany removes every match.
{}matches everything. - findOneAndDelete removes one document and returns it, handy when you need what you removed.
- The legacy
remove()is deprecated.
bulkWrite sends a list of write operations in one request:
db.books.bulkWrite([
{ insertOne: { document: { title: "Kindred", stock: 4 } } },
{ updateOne: { filter: { _id: 4 }, update: { $inc: { price: -1 } } } },
{ deleteMany: { filter: { stock: 0 } } }
], { ordered: true })It supports insertOne, updateOne, updateMany, replaceOne, deleteOne and deleteMany. Ordered (the default) runs them in sequence and stops at the first error; unordered attempts them all. It is not a transaction: operations that succeeded stay done.
The shortcut
Before any delete, run the same filter through countDocuments. The number you see is the number you will lose.
Write the filter
{ stock: 0 }.
The trap: deleteMany() with an empty filter "to test it". {} matches every document.
Drills
Answer fast — trust the rule.
After db.books.deleteMany({}), what remains?
What is deletedCount for db.books.deleteMany({ year: { $lt: 1950 } })?
Why is deleteOne({ genres: "classic" }) risky?
An ordered bulkWrite has 4 operations and the 2nd fails. What happens?
Remember
- Delete with the filter you have already read; batch many writes in one bulkWrite.
- Shortcut: countDocuments with the same filter first; the number you see is the number you lose.
- Trap:
{}matches everything, and bulkWrite does not roll back what already succeeded.
