MongoDB Delete
deleteOne() and deleteMany() remove documents from a collection permanently based on a filter, with no built-in undo, so precise filters matter more here than anywhere else.
deleteOne(): Removing a Single Document
db.collection.deleteOne(filter) removes the first document that matches filter. If multiple documents match, only one is removed — the one MongoDB happens to encounter first, which is not guaranteed to be any particular one unless your filter targets a unique field like _id.
Delete a single document by its unique id
db.sessions.deleteOne({ _id: ObjectId('64f1a2b3c4d5e6f7a8b9c0d1') })deleteMany(): Removing Every Match
deleteMany(filter) removes every document that matches the filter. It's the same shape as deleteOne but with much larger blast radius, since a broad or mistaken filter can wipe out far more data than intended. Passing an empty filter, {}, deletes every document in the collection while leaving the collection and its indexes in place.
Delete every matching document, and every document
// Remove all expired sessions
db.sessions.deleteMany({ expiresAt: { $lt: new Date() } })
// Remove every document in the collection (indexes remain)
db.tempLogs.deleteMany({})Inspecting the Delete Result
Delete operations return a result object with a deletedCount field, telling you exactly how many documents were removed. There is no way to retrieve the deleted documents afterward through this call — if you need the data for auditing or rollback, read it with find() first, or use findOneAndDelete() to fetch and delete in a single atomic step.
- deleteOne(filter) — removes at most one matching document
- deleteMany(filter) — removes every matching document
- deleteMany({}) — clears the collection but keeps it and its indexes
- findOneAndDelete(filter) — deletes and returns the deleted document atomically
Delete and get the removed document back atomically
const removed = db.carts.findOneAndDelete({ userId: 'u-501' })
print(removed)Exercise: MongoDB Delete
What does deleteMany({}) do to a collection?