How can I update and increment two fields in one command in MongoDB?


Let us first create a collection with documents −

> db.incrementDemo.insertOne({"Value1":10,"Value2":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbdaf07de8cc557214c0e15")
}

Display all documents from a collection with the help of find() method. The query is as follows −

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

This will produce the following output −

{
   "_id" : ObjectId("5cbdaf07de8cc557214c0e15"),
   "Value1" : 10,
   "Value2" : 20
}

Following is the query to increment two fields in one command in MongoDB −

> db.incrementDemo.update({},{ $inc : { Value1 : 1, Value2 : 1 } });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check both the fields have been incremented with value 1 or not −

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

This will produce the following output −

{
   "_id" : ObjectId("5cbdaf07de8cc557214c0e15"),
   "Value1" : 11,
   "Value2" : 21
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

228 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements