spondbob
spondbob

Reputation: 1633

Increase multiple values in nested array

I have a simple product schema

{
  "_id": "123",
  "purchased": 0,
  "options": [
    {
      "name": "Size",
      "options": [
        {
          "name": "S",
          "purchased": 0
        },
        {
          "name": "M",
          "purchased": 0
        }
      ]
    },
    {
      "name": "Color",
      "options": [
        {
          "name": "Red",
          "purchased": 0
        },
        {
          "name": "Blue",
          "purchased": 0
        }
      ]
    }
  ]
}

Let's say a customer purchase 1 item of Size M color Red. How do I $inc the purchased value for each option and for the product itself?

P.S I am running mongo version 3.2.4

Upvotes: 2

Views: 236

Answers (1)

s7vr
s7vr

Reputation: 75964

Looks like updating may be your only option. If you choose to update you can try something like below in mongo 3.6 version.

Finds the document with filter criteria and update which includes new positional identifier to update matching elements in array inside update method.

Use arrayFilter options for applying query criteria on nested array to control what elements to update.

You may have to do two updates one for each Size and Color. Don't think you can update multiple elements of same array for different criteria.

For Size

db.getCollection('col').update( {} , { '$inc': { 'purchased': 1, 'options.$[type].options.$[option]purchased': 1 } }, { arrayFilters:[ { 'type.name': ‘Size' }, {'option.name':'S' }] })

For Color

db.getCollection('col').update( {} , { '$inc': { 'purchased': 1, 'options.$[type].options.$[option]purchased': 1 } }, { arrayFilters:[ { 'type.name': ‘Color' }, {'option.name':'Red' }] })

Upvotes: 2

Related Questions