Conditional update depending on field matched in MongoDB


For conditional update, use update() and set new value using $set. Let us create a collection with documents −

> db.demo150.insertOne({"StudentId":101,"StudentName":"Chris","StudentMarks":35});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e350dcdfdf09dd6d08539d3")
}
> db.demo150.insertOne({"StudentId":102,"StudentName":"Chris","StudentMarks":55});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e350dcefdf09dd6d08539d4")
}
> db.demo150.insertOne({"StudentId":103,"StudentName":"David","StudentMarks":34});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e350dcffdf09dd6d08539d5")
}
> db.demo150.insertOne({"StudentId":104,"StudentName":"Chris","StudentMarks":38});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e350dd0fdf09dd6d08539d6")
}

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

> db.demo150.find();

This will produce the following output −

{ "_id" : ObjectId("5e350dcdfdf09dd6d08539d3"), "StudentId" : 101, "StudentName" : "Chris", "StudentMarks" : 35 }
{ "_id" : ObjectId("5e350dcefdf09dd6d08539d4"), "StudentId" : 102, "StudentName" : "Chris", "StudentMarks" : 55 }
{ "_id" : ObjectId("5e350dcffdf09dd6d08539d5"), "StudentId" : 103, "StudentName" : "David", "StudentMarks" : 34 }
{ "_id" : ObjectId("5e350dd0fdf09dd6d08539d6"), "StudentId" : 104, "StudentName" : "Chris", "StudentMarks" : 38 }

Following is the query for conditional update depending on field matched −

> db.demo150.update({"StudentId":103},{$set:{"StudentMarks":97}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo150.find();

This will produce the following output −

{ "_id" : ObjectId("5e350dcdfdf09dd6d08539d3"), "StudentId" : 101, "StudentName" : "Chris", "StudentMarks" : 35 }
{ "_id" : ObjectId("5e350dcefdf09dd6d08539d4"), "StudentId" : 102, "StudentName" : "Chris", "StudentMarks" : 55 }
{ "_id" : ObjectId("5e350dcffdf09dd6d08539d5"), "StudentId" : 103, "StudentName" : "David", "StudentMarks" : 97 }
{ "_id" : ObjectId("5e350dd0fdf09dd6d08539d6"), "StudentId" : 104, "StudentName" : "Chris", "StudentMarks" : 38 }

Updated on: 01-Apr-2020

360 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements