0
0
MongodbHow-ToBeginner · 4 min read

How to Use findOneAndUpdate in MongoDB: Syntax and Examples

Use findOneAndUpdate in MongoDB to find a single document and update it atomically. It takes a filter to select the document, an update operation to apply, and optional settings like returnDocument to control the returned result.
📐

Syntax

The findOneAndUpdate method has three main parts:

  • filter: A query object to find the document.
  • update: The changes to apply, usually with update operators like $set.
  • options: Optional settings such as returnDocument to specify if the updated or original document is returned.
javascript
db.collection.findOneAndUpdate(filter, update, options)
💻

Example

This example finds a user with name: 'Alice' and updates her age to 30. It returns the updated 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 document
    await users.insertOne({ name: 'Alice', age: 25 });

    // Update age and return updated document
    const result = await users.findOneAndUpdate(
      { name: 'Alice' },
      { $set: { age: 30 } },
      { returnDocument: 'after' }
    );

    console.log(result.value);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
Output
{"_id": "<ObjectId>", "name": "Alice", "age": 30}
⚠️

Common Pitfalls

Common mistakes include:

  • Not using update operators like $set, which replaces the whole document instead of updating fields.
  • Forgetting to set returnDocument: 'after' if you want the updated document returned.
  • Not handling the case when no document matches the filter, which returns null.
javascript
/* Wrong: Replaces whole document */
db.collection.findOneAndUpdate(
  { name: 'Bob' },
  { age: 40 }
);

/* Right: Uses $set to update only age */
db.collection.findOneAndUpdate(
  { name: 'Bob' },
  { $set: { age: 40 } }
);
📊

Quick Reference

  • filter: Selects the document to update.
  • update: Use update operators like $set, $inc.
  • options: returnDocument: 'after' returns updated doc, default is original.
  • Returns: An object with value property holding the document.

Key Takeaways

Always use update operators like $set to modify fields without replacing the whole document.
Set returnDocument: 'after' option to get the updated document returned.
findOneAndUpdate returns null if no document matches the filter.
It performs the find and update atomically in one operation.
Use options to control behavior like upsert or projection.