Increment value of an array element with array object in MongoDB


To increment the value of an array object, use $inc. Let us create a collection with documents −

>db.demo506.insertOne({"details":[{id:1,Quantity:4},{id:2,Quantity:3},{id:3,Quantity:2},{id:4,Qua ntity:7}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e882ed6987b6e0e9d18f576")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e882ed6987b6e0e9d18f576"),
   "details" : [
      {
         "id" : 1,
         "Quantity" : 4
      },
      {
         "id" : 2,
         "Quantity" : 3
      },
      {
         "id" : 3,
         "Quantity" : 2
      },
      {
         "id" : 4,
         "Quantity" : 7
      }
   ]
}

Following is the query to increment the value of an array element name quantity with array object −

> db.demo506.update({"details.id":2},{$inc:{"details.$.Quantity":10}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e882ed6987b6e0e9d18f576"),
   "details" : [
      {
         "id" : 1,
         "Quantity" : 4
      },
      {
         "id" : 2,
         "Quantity" : 13
      },
      {
         "id" : 3,
         "Quantity" : 2
      },
      {
         "id" : 4,
         "Quantity" : 7
      }
   ]
}

Updated on: 13-May-2020

603 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements