← Back to MongoDB Course | Chapter 5: CRUD — Delete | Lesson 3 of 6

findOneAndDelete()

findOneAndDelete removes a document and returns it, in one atomic step.

In this page:

  1. findOneAndDelete()
Syntax
javascript
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()

bash
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
  1. Using find then deleteOne, creating a race
  2. Forgetting sort for queue order
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.