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
Selected Reading
MongoDB findOneAndUpdate() to update a single document
The findOneAndUpdate() method is used to update only a single document in MongoDB. It finds the first document that matches the query criteria and updates it, returning either the original or updated document.
Syntax
db.collection.findOneAndUpdate(
filter,
update,
options
)
Sample Data
Let us create a collection with student documents ?
db.demo349.insertMany([
{"Name": "Chris", "Marks": 56},
{"Name": "David", "Marks": 78},
{"Name": "Chris", "Marks": 89},
{"Name": "David", "Marks": 54}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e55384af8647eb59e5620b4"),
ObjectId("5e553853f8647eb59e5620b5"),
ObjectId("5e55385af8647eb59e5620b6"),
ObjectId("5e55385ff8647eb59e5620b7")
]
}
Display all documents from the collection ?
db.demo349.find();
{ "_id": ObjectId("5e55384af8647eb59e5620b4"), "Name": "Chris", "Marks": 56 }
{ "_id": ObjectId("5e553853f8647eb59e5620b5"), "Name": "David", "Marks": 78 }
{ "_id": ObjectId("5e55385af8647eb59e5620b6"), "Name": "Chris", "Marks": 89 }
{ "_id": ObjectId("5e55385ff8647eb59e5620b7"), "Name": "David", "Marks": 54 }
Example: Update Single Document
The following query updates the first David's marks by incrementing them by 10 ?
db.demo349.findOneAndUpdate(
{ "Name": "David" },
{ $inc: { Marks: 10 } }
);
{
"_id": ObjectId("5e553853f8647eb59e5620b5"),
"Name": "David",
"Marks": 78
}
Verify Result
Check the updated collection ?
db.demo349.find();
{ "_id": ObjectId("5e55384af8647eb59e5620b4"), "Name": "Chris", "Marks": 56 }
{ "_id": ObjectId("5e553853f8647eb59e5620b5"), "Name": "David", "Marks": 88 }
{ "_id": ObjectId("5e55385af8647eb59e5620b6"), "Name": "Chris", "Marks": 89 }
{ "_id": ObjectId("5e55385ff8647eb59e5620b7"), "Name": "David", "Marks": 54 }
Key Points
-
findOneAndUpdate()updates only the first matching document, not all matching documents - Returns the document before the update by default
- Use
returnDocument: "after"option to return the updated document
Conclusion
The findOneAndUpdate() method efficiently updates a single document and returns it in one operation. It's ideal when you need both update functionality and immediate access to the document data.
Advertisements
