Skip to content

CRUD

deleteOne() and deleteMany()

Removing documents, the danger of an empty filter, and when a soft delete is the better model.

BeginnerAbout 4 minutes

deleteOne removes the first match. deleteMany removes every match. The argument is a filter, same as find. There is no 'recycle bin' unless you build one.

db.orders.deleteOne({
  userId: ObjectId("64a1b2c3d4e5f6a7b8c90001"),
  status: "pending"
})
Remove one pending order
{ acknowledged: true, deletedCount: 1 }

deletedCount: 0 means the filter missed — not an exception. Check it when the caller thought the document existed.

Soft delete

Users and orders are often not deleted. You $set: { isActive: false } (or deletedAt: ISODate(...)) and every find includes { isActive: true }. Hard delete for data you are sure you will never audit — temp jobs, expired cache docs, a mistyped insert you caught immediately.

db.users.updateOne(
  { email: "rahul@example.com" },
  { $set: { isActive: false } }
)
Prefer this for accounts

Interview question

When would you delete a document versus setting isActive: false?

Think about it first.

Interview question

Why is deleteMany({}) dangerous?

Think about it first.