findOneAndDelete()
findOneAndDelete removes a document and returns it, in one atomic step.
In this page:
Syntax
db.collection_name.findOneAndDelete(filter)
findOneAndDelete()
It returns the deleted document (or null), which is perfect for job queues where a worker claims the next item. Use sort to control which matching document is taken and projection to limit fields returned.
Note:
Combine with sort to pop the oldest item from a queue.
Example: findOneAndDelete()
test> db.jobs.insertMany([{ _id: 1, task: "email", prio: 2 }, { _id: 2, task: "resize", prio: 1 }, { _id: 3, task: "backup", prio: 3 }])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3 } }
test> db.jobs.findOneAndDelete({ prio: { $gte: 1 } })
{ _id: 1, task: 'email', prio: 2 }
test> db.jobs.findOneAndDelete({ task: "missing" })
null
test> db.jobs.countDocuments()
2
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Using find then deleteOne, creating a race
- Forgetting sort for queue order
- Ignoring a null result
Chapter Summary
- Deletes and returns the document
- Atomic per document
- sort picks which one
- Returns null when nothing matched
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: