Update the last row with search criteria in MongoDB?

To update the last row that matches specific search criteria in MongoDB, use the findAndModify() method with a sort parameter to identify the most recent document.

Syntax

db.collection.findAndModify({
    query: { field: "value" },
    sort: { _id: -1 },
    update: { $set: { field: "newValue" } },
    new: true
});

Sample Data

db.demo516.insertMany([
    { "Name": "John", "Age": 22, "Score": 56 },
    { "Name": "John", "Age": 23, "Score": 67 },
    { "Name": "John", "Age": 22, "Score": 56 },
    { "Name": "John", "Age": 22, "Score": 66 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e889fdb987b6e0e9d18f591"),
        ObjectId("5e889ff1987b6e0e9d18f592"),
        ObjectId("5e889ff3987b6e0e9d18f593"),
        ObjectId("5e889ffa987b6e0e9d18f594")
    ]
}

Display Current Documents

db.demo516.find();
{ "_id": ObjectId("5e889fdb987b6e0e9d18f591"), "Name": "John", "Age": 22, "Score": 56 }
{ "_id": ObjectId("5e889ff1987b6e0e9d18f592"), "Name": "John", "Age": 23, "Score": 67 }
{ "_id": ObjectId("5e889ff3987b6e0e9d18f593"), "Name": "John", "Age": 22, "Score": 56 }
{ "_id": ObjectId("5e889ffa987b6e0e9d18f594"), "Name": "John", "Age": 22, "Score": 66 }

Update Last Matching Document

Update the last document where Name is "John" and Age is 22 ?

db.demo516.findAndModify({
    query: { Name: "John", Age: 22 },
    sort: { _id: -1 },
    update: { $set: { Score: 98 } },
    new: true
});
{
    "_id": ObjectId("5e889ffa987b6e0e9d18f594"),
    "Name": "John",
    "Age": 22,
    "Score": 98
}

Verify Result

db.demo516.find();
{ "_id": ObjectId("5e889fdb987b6e0e9d18f591"), "Name": "John", "Age": 22, "Score": 56 }
{ "_id": ObjectId("5e889ff1987b6e0e9d18f592"), "Name": "John", "Age": 23, "Score": 67 }
{ "_id": ObjectId("5e889ff3987b6e0e9d18f593"), "Name": "John", "Age": 22, "Score": 56 }
{ "_id": ObjectId("5e889ffa987b6e0e9d18f594"), "Name": "John", "Age": 22, "Score": 98 }

Key Points

  • sort: { _id: -1 } ensures the last inserted matching document is selected
  • new: true returns the updated document instead of the original
  • Only one document is updated even if multiple documents match the criteria

Conclusion

Use findAndModify() with descending sort on _id to update the most recently inserted document that matches your search criteria. The sort parameter is crucial for targeting the last matching row.

Updated on: 2026-03-15T03:21:44+05:30

444 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements