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.