0
0
MongodbHow-ToBeginner · 4 min read

How to Use findOneAndDelete in MongoDB: Syntax and Examples

Use findOneAndDelete(filter, options) in MongoDB to find a single document matching the filter and delete it atomically. It returns the deleted document if found, or null if no match exists.
📐

Syntax

The findOneAndDelete method takes two main arguments:

  • filter: An object specifying the criteria to find the document.
  • options (optional): Additional settings like projection to specify fields to return, or sort to choose which document to delete if multiple match.

It returns the deleted document or null if no document matches.

mongodb
db.collection.findOneAndDelete(filter, options)
💻

Example

This example finds and deletes the first user with the name 'Alice' from the 'users' collection and returns the deleted document.

javascript
const { MongoClient } = require('mongodb');

async function run() {
  const client = new MongoClient('mongodb://localhost:27017');
  try {
    await client.connect();
    const db = client.db('testdb');
    const users = db.collection('users');

    // Insert sample data
    await users.insertMany([
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 30 }
    ]);

    // Find and delete one document where name is 'Alice'
    const result = await users.findOneAndDelete({ name: 'Alice' });

    console.log('Deleted document:', result.value);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
Output
Deleted document: { _id: ObjectId("..."), name: 'Alice', age: 25 }
⚠️

Common Pitfalls

  • Not handling the case when no document matches the filter, which returns null in result.value.
  • Using findOneAndDelete without await or proper promise handling in async code.
  • Expecting multiple documents to be deleted; findOneAndDelete deletes only one document.
  • Not specifying sort option when multiple documents match, which may lead to unexpected document deletion.
javascript
/* Wrong: Not awaiting the async call */
const result = users.findOneAndDelete({ name: 'Alice' });
console.log(result.value); // undefined or Promise object

/* Right: Await the async call */
const result = await users.findOneAndDelete({ name: 'Alice' });
console.log(result.value); // deleted document or null
📊

Quick Reference

ParameterDescription
filterObject to match the document to delete
optionsOptional settings like projection, sort, maxTimeMS
ReturnObject with 'value' field containing deleted document or null

Key Takeaways

Use findOneAndDelete to atomically find and delete a single document matching a filter.
Always await the method in async code to get the deleted document result.
If no document matches, the method returns null in the value field.
Use the sort option to control which document is deleted when multiple match.
findOneAndDelete deletes only one document, not multiple.