Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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: truereturns 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.
Advertisements
