CRUD
deleteOne() and deleteMany()
Removing documents, the danger of an empty filter, and when a soft delete is the better model.
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"
}){ 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 } }
)Interview question
When would you delete a document versus setting isActive: false?
Hard delete when the data should not come back and has no audit trail — a bad insert, a temp collection. Soft delete for users, orders, anything legal or support might ask about. Then every read has to include the active filter.
Interview question
Why is deleteMany({}) dangerous?
An empty filter matches every document. deleteMany will remove the collection's data. I treat it like DELETE FROM users with no WHERE — I would not run it in production without an explicit, reviewed filter.