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() is used to update only a single document in MongoDB. Let us create a collection with documents −
db.demo349.insertOne({"Name":"Chris","Marks":56});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e55384af8647eb59e5620b4")
}
> db.demo349.insertOne({"Name":"David","Marks":78});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e553853f8647eb59e5620b5")
}
> db.demo349.insertOne({"Name":"Chris","Marks":89});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e55385af8647eb59e5620b6")
}
> db.demo349.insertOne({"Name":"David","Marks":54});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e55385ff8647eb59e5620b7")
}
Display all documents from a collection with the help of find() method −
> db.demo349.find();
This will produce the following output −
{ "_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 }
Following is the query to work with findOneAndUpdate in MongoDB −
> db.demo349.findOneAndUpdate({ "Name" : "David" },{$inc:{Marks:10}});
{
"_id" : ObjectId("5e553853f8647eb59e5620b5"),
"Name" : "David",
"Marks" : 78
}
Display all documents from a collection with the help of find() method −
> db.demo349.find();
This will produce the following output −
{ "_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 } Advertisements
