How to dynamically updateMany array

My data structure is like this

    {
      items: [
        {
          identity: Number,
          acc: Number
        },
        ...
      ]
    }

And if the user’s request comes like this

    [
      {
        _id: @@@,
        identity: 1,
        acc: 3
      },
      {
        _id: ###,
        identity: 7,
        acc: 5
      }
    ]

I want to do acc+=3 for data with identity 1 among items with _id @@@, and acc+=5 for data with identity 5 among items with _id ###.

Is it possible with one query? and If that’s not possible, should I iterate over the number of arrays requested by the user?

Please provide real sample documents. We cannot easily import documents with _id:### and _id:@@@. The three dots to indicate the presence of other object withing the array is an extra step.

Next time just publish as:

{
      _id : 1000 ,
      /* I have added _id because I think you want to match the
         the _id from the requests.
      */
      items: [
        {
          identity: 1,
          acc: 100
        },
        /* ... having the 2 dots within a comments works fine */
        {
          identity: 7 ,
          acc: 200
        }
      ]
    }
    /* And the requests */
 [
      {
        _id : 1000 ,
        identity: 1,
        acc: 3
      },
      {
        _id: 1001 ,
        identity: 7 ,
        acc: 5
      }
    ]
   /* And the result */
{
      _id : 1000 ,
      items: [
        {
          identity : 1 ,
          acc: 103 /* incremented because _id and identity matches */
        },
        /* ... */
        {
          identity: 7 ,
          acc: 200 /* unchanged because _id does not match */
        }
      ]
    }

Do I understand correctly the problem statement?

Hi, I’m new to mongodb and I got the same problem at this point, do you have the solution for this issue @steevej . If yes, I would be very grateful for your answer, I stuck here for a while

Create a new thread with your case along with example documents so you’ll get the best help. People have limited time so if you can provide actual sample documents they can quickly work with that to play about.

Try creating some documents here and then link to the playground:

Also, try not to necro threads from several years ago as you’ll get more visibility on a new thread!

1 Like