Increment a property value of an element in array object with MongoDB


To increment a property value of an element, use update() in MongoDB and in that, work with #$inc to increment. Let us first create a collection with documents −

> db.demo97.insertOne({
...    "Details": [
...       {
...          "Name": "Chris",
...          "Marks": 45
...       },
...       {
...          "Name": "Bob",
...          "Marks": 88
...       }y
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2d6d24b8903cdd865577af")
}

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

> db.demo97.find();

This will produce the following output −

{ "_id" : ObjectId("5e2d6d24b8903cdd865577af"), "Details" : [ { "Name" : "Chris", "Marks" : 45 }, { "Name" : "Bob", "Marks" : 88 } ] }

Following is the query to increment a property value of an element in array object −

> db.demo97.update(
...    { "Details.Name": "Bob"},
...    { $inc: { "Details.$.Marks" : 10 } }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo97.find();

This will produce the following output −

{ "_id" : ObjectId("5e2d6d24b8903cdd865577af"), "Details" : [ { "Name" : "Chris", "Marks" : 45 }, { "Name" : "Bob", "Marks" : 98 } ] }

Updated on: 30-Mar-2020

434 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements