Using findOneAndUpdate () to update in MongoDB?


The findOneAndUpdate() is used to update a single document based on the filter and sort criteria i.e. −

db.collection.findOneAndUpdate(filter, update, options)

Let us create a collection with documents −

> db.demo328.insertOne({Name:"Chris",Marks:67});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e516b19f8647eb59e56207a")
}
> db.demo328.insertOne({Name:"David",Marks:78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e516b24f8647eb59e56207b")
}
> db.demo328.insertOne({Name:"Bob",Marks:97});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e516b2bf8647eb59e56207c")
}

Display all documents from a collection with the help of find() method −

> db.demo328.find();

This will produce the following output −

{ "_id" : ObjectId("5e516b19f8647eb59e56207a"), "Name" : "Chris", "Marks" : 67 }
{ "_id" : ObjectId("5e516b24f8647eb59e56207b"), "Name" : "David", "Marks" : 78 }
{ "_id" : ObjectId("5e516b2bf8647eb59e56207c"), "Name" : "Bob", "Marks" : 97 }

Following is the query to update with findOneAndUpdate(). Here, we are incrementing a specific document’s field Marks −

> db.demo328.findOneAndUpdate({Name:"David"},{ $inc: { "Marks" : 10} });
{
   "_id" : ObjectId("5e516b24f8647eb59e56207b"),
   "Name" : "David",
   "Marks" : 78
}

Display all documents from a collection with the help of find() method −

> db.demo328.find();

This will produce the following output −

{ "_id" : ObjectId("5e516b19f8647eb59e56207a"), "Name" : "Chris", "Marks" : 67 }
{ "_id" : ObjectId("5e516b24f8647eb59e56207b"), "Name" : "David", "Marks" : 88 }
{ "_id" : ObjectId("5e516b2bf8647eb59e56207c"), "Name" : "Bob", "Marks" : 97 }

Updated on: 02-Apr-2020

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements