krzysu
krzysu

Reputation: 402

How to update subarray field of array in mongodb

My object looks like this:

Stats = {
  name: 'filters'
  variants: [
    {
      variant: 'A'
      displayed: 123
      actions: [
        {
          name: 'clicked'
          triggered: 12
        }

      ]
    },
    {
      variant: 'B'
      displayed: 123
      actions: [
        {
          name: 'clicked'
          triggered: 12
        }
      ]
    }
  ]
}

I have an array of variants and inside it array of actions. I would like to increment triggered field for selected variant and actions.name. I am using that in meteor.js.

My find query looks like below:

Stats.find({
  name: 'filters', 
  variants: {
    $elemMatch: {
      variant: 'A',
      'actions.name': 'clicked'
}}})

Now if object exists I would like to do something like below, but I know it doesn't work.

Stats.update({
  name: 'filters', 
  variants: {
    $elemMatch: {
      variant: 'A',
      'actions.name': 'clicked'
}}},
{
  $inc: {
    'variants.$.actions.$.triggered': 1
}})

I know that the positional $ operator acts as a placeholder for the first match of the update query selector. But maybe you have any other idea how to do it?

Upvotes: 2

Views: 1525

Answers (2)

krzysu
krzysu

Reputation: 402

I ended up with flattening the structure to:

Stats = [
  {
    name: 'filters'
    variant: 'A'
    displayed: 123
    actions: [
      {
        name: 'clicked'
        triggered: 12
      }
    ]
  },
  {
    name: 'filters'
    variant: 'B'
    displayed: 123
    actions: [
      {
        name: 'clicked'
        triggered: 12
      }
    ]
  }
]

and here I can increment the triggered value easily:

Stats.update({
  name: 'filters',
  variant: 'A',
  'actions.name': 'clicked'
}, {
  $inc:  {
    'actions.$.triggered': 1
}})

I am using this code on server side only. Anyway, thanks for help!

Upvotes: 1

Tarang
Tarang

Reputation: 75945

At the moment the $ operator isn't available on minimongo and even on the server there are a couple of glitches with it (at least when I used it last).

Its a known issue and it looks like it may be fixed soon: https://github.com/meteor/meteor/issues/153

Upvotes: 0

Related Questions