How to increment inside the update() function in MongoDB?


You can use $inc operator to increment. Let us first create a collection with documents −

> db.addInUpdateFunctionDemo.insertOne({"PlayerName":"Chris","PlayerScore":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2b3f4345990cee87fd893")
}
> db.addInUpdateFunctionDemo.insertOne({"PlayerName":"Robert","PlayerScore":88});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2b3fc345990cee87fd894")
}
> db.addInUpdateFunctionDemo.insertOne({"PlayerName":"David","PlayerScore":99});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2b407345990cee87fd895")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.addInUpdateFunctionDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd2b3f4345990cee87fd893"),
   "PlayerName" : "Chris",
   "PlayerScore" : 78
}
{
   "_id" : ObjectId("5cd2b3fc345990cee87fd894"),
   "PlayerName" : "Robert",
   "PlayerScore" : 88
}
{
   "_id" : ObjectId("5cd2b407345990cee87fd895"),
   "PlayerName" : "David",
   "PlayerScore" : 99
}

Following is the query to perform addition inside the update() function in MongDB −

> db.addInUpdateFunctionDemo.update({_id : ObjectId("5cd2b407345990cee87fd895")},{$inc: {PlayerScore: 201}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check all the documents once again −

> db.addInUpdateFunctionDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd2b3f4345990cee87fd893"),
   "PlayerName" : "Chris",
   "PlayerScore" : 78
}
{
   "_id" : ObjectId("5cd2b3fc345990cee87fd894"),
   "PlayerName" : "Robert",
   "PlayerScore" : 88
}
{
   "_id" : ObjectId("5cd2b407345990cee87fd895"),
   "PlayerName" : "David",
   "PlayerScore" : 300
}

Updated on: 30-Jul-2019

197 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements