Skip to the workspace
Pebellslearn by building
Collections & Methods  ›  Capstone Project

Deleting Documents and bulkWrite

delete() and relevant 15 mindeleteOne and deleteMany remove documents that match a filter, drop removes the whole collection, and bulkWrite sends many inserts, updates and deletes in one ordered or unordered request.

mongodb / Deleting Documents and bulkWrite

Explore each scene at your own pace.

01 · The rule

The rule

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.