Amani
Amani

Reputation: 247

Mongoose increment subdocument array value within another subdocument array

I have a document like this

_id:'111'
products:[
   {
    _id:'pqr'
    nums:[
      {_id:'aaa',
      quantity:50
      },
      {_id:'bbb',
       quantity:50
      }
    ]
   }
]

The document above can be summarized like this below for easy understanding.

   _id
   products: [
      nums: [
        {}, //quantity is in this object
        {}
      ]
   ]

I need to increment the value of quantity in nums subdocument which is in products subdocument based on its _id.

This is what I have tried so far but it doesn't work as I don't know how to catch the _id inside nums object so as to update the specific object in that sub-subdocument array.

Shop.findOneAndUpdate(
       { "_id": '111', "products._id": 'pqr'  },
          {
            "$inc": {
               "products.$[].nums.quantity": 1
            }
    }
)

How can I achieve this?

Upvotes: 1

Views: 382

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17935

Using arrayfilters in update operation :

db.getCollection("collectionName").findOneAndUpdate(
  { _id: "111" }, // Querying against `_id`, need to convert string to `ObjectId()` or instead use `.findByIdAndUpdate()`
  { $inc: { "products.$[p].nums.$[n].quantity": 1 } },
  {
    arrayFilters: [{ "p._id": "pqr" }, { "n._id": "aaa" }] // Inputs here
  }
  // Use { new : true } Option in mongoose to return updated document
);

Input doc :

{
    "_id" : "111",
    "products" : [ 
        {
            "_id" : "pqr",
            "nums" : [ 
                {
                    "_id" : "aaa",
                    "quantity" : 50
                }, 
                {
                    "_id" : "bbb",
                    "quantity" : 50
                }
            ]
        }, 
        {
            "_id" : "abc",
            "nums" : [ 
                {
                    "_id" : "aaa1",
                    "quantity" : 501
                }, 
                {
                    "_id" : "bbb1",
                    "quantity" : 501
                }
            ]
        }
    ]
}

Output doc :

{
    "_id" : "111",
    "products" : [ 
        {
            "_id" : "pqr",
            "nums" : [ 
                {
                    "_id" : "aaa",
                    "quantity" : 51 // This got incremented
                }, 
                {
                    "_id" : "bbb",
                    "quantity" : 50
                }
            ]
        }, 
        {
            "_id" : "abc",
            "nums" : [ 
                {
                    "_id" : "aaa1",
                    "quantity" : 501
                }, 
                {
                    "_id" : "bbb1",
                    "quantity" : 501
                }
            ]
        }
    ]
}

Ref : mongoose's .findByIdAndUpdate()

Upvotes: 1

Related Questions