Using findOneAndUpdate () to update in MongoDB?

The findOneAndUpdate() method updates a single document based on the filter criteria and returns the document (either the original or modified version based on options).

Syntax

db.collection.findOneAndUpdate(filter, update, options)
  • filter ? Query criteria to match the document
  • update ? Update operations to perform
  • options ? Optional parameters like returnNewDocument, sort, etc.

Sample Data

Let us create a collection with sample documents ?

db.demo328.insertMany([
    {Name: "Chris", Marks: 67},
    {Name: "David", Marks: 78},
    {Name: "Bob", Marks: 97}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e516b19f8647eb59e56207a"),
        ObjectId("5e516b24f8647eb59e56207b"),
        ObjectId("5e516b2bf8647eb59e56207c")
    ]
}

Display all documents from the collection ?

db.demo328.find();
{ "_id": ObjectId("5e516b19f8647eb59e56207a"), "Name": "Chris", "Marks": 67 }
{ "_id": ObjectId("5e516b24f8647eb59e56207b"), "Name": "David", "Marks": 78 }
{ "_id": ObjectId("5e516b2bf8647eb59e56207c"), "Name": "Bob", "Marks": 97 }

Example: Update Using findOneAndUpdate()

Update David's marks by incrementing them by 10 ?

db.demo328.findOneAndUpdate(
    {Name: "David"},
    { $inc: { "Marks": 10 } }
);
{
    "_id": ObjectId("5e516b24f8647eb59e56207b"),
    "Name": "David",
    "Marks": 78
}

Verify the update by displaying all documents ?

db.demo328.find();
{ "_id": ObjectId("5e516b19f8647eb59e56207a"), "Name": "Chris", "Marks": 67 }
{ "_id": ObjectId("5e516b24f8647eb59e56207b"), "Name": "David", "Marks": 88 }
{ "_id": ObjectId("5e516b2bf8647eb59e56207c"), "Name": "Bob", "Marks": 97 }

Key Points

  • findOneAndUpdate() returns the original document by default (before update)
  • Use {returnNewDocument: true} option to return the updated document
  • Only updates the first matching document based on the filter criteria

Conclusion

The findOneAndUpdate() method provides an atomic way to update a single document and retrieve it in one operation. By default, it returns the original document before modification.

Updated on: 2026-03-15T02:31:06+05:30

368 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements