MongoDB query to increment a specific value using custom variable


Set a custom variable and use update() along with $inc to increment. Let us create a collection with documents −

> db.demo271.insertOne({"Marks":56});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4821211627c0c63e7dbabc")
}
> db.demo271.insertOne({"Marks":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4821241627c0c63e7dbabd")
}
> db.demo271.insertOne({"Marks":72});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e48212b1627c0c63e7dbabe")
}

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

> db.demo271.find();

This will produce the following output −

{ "_id" : ObjectId("5e4821211627c0c63e7dbabc"), "Marks" : 56 }
{ "_id" : ObjectId("5e4821241627c0c63e7dbabd"), "Marks" : 78 }
{ "_id" : ObjectId("5e48212b1627c0c63e7dbabe"), "Marks" : 72 }

Following is the query to increment using a custom variable −

> var incrementValue=10;
> db.demo271.update(
...   { Marks: 78 },
...   { $inc: { Marks:incrementValue } }
...)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo271.find();

This will produce the following output −

{ "_id" : ObjectId("5e4821211627c0c63e7dbabc"), "Marks" : 56 }
{ "_id" : ObjectId("5e4821241627c0c63e7dbabd"), "Marks" : 88 }
{ "_id" : ObjectId("5e48212b1627c0c63e7dbabe"), "Marks" : 72 }

Updated on: 31-Mar-2020

366 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements