Increment only a single value in MongoDB document?


To update only a single value and increment it in MongoDB, use $inc along with update(). Let us create a collection with documents −

> db.demo698.insertOne({Score:78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6d8a4551299a9f98c9398")
}
> db.demo698.insertOne({Score:56});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6d8a7551299a9f98c9399")
}
> db.demo698.insertOne({Score:65});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6d8aa551299a9f98c939a")
}
> db.demo698.insertOne({Score:88});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6d8b0551299a9f98c939b")
}

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

> db.demo698.find();

This will produce the following output −

{ "_id" : ObjectId("5ea6d8a4551299a9f98c9398"), "Score" : 78 }
{ "_id" : ObjectId("5ea6d8a7551299a9f98c9399"), "Score" : 56 }
{ "_id" : ObjectId("5ea6d8aa551299a9f98c939a"), "Score" : 65 }
{ "_id" : ObjectId("5ea6d8b0551299a9f98c939b"), "Score" : 88 }

Following is the query to increment only a single value −

> db.demo698.update({_id:ObjectId("5ea6d8b0551299a9f98c939b")},{$inc:{Score:12}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo698.find();

This will produce the following output −

{ "_id" : ObjectId("5ea6d8a4551299a9f98c9398"), "Score" : 78 }
{ "_id" : ObjectId("5ea6d8a7551299a9f98c9399"), "Score" : 56 }
{ "_id" : ObjectId("5ea6d8aa551299a9f98c939a"), "Score" : 65 }
{ "_id" : ObjectId("5ea6d8b0551299a9f98c939b"), "Score" : 100 }

Updated on: 14-May-2020

80 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements