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
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.
Advertisements
