'Incrementing multiple array values in an object MongoDB

I've been at this for a while now. Trying to update multiple array values, in the same object, with a single query.

Database data looks like this:

  id: 616f5aca5f60da8bb5870e36
  title: "title"
  recommendations: {
    616f65705f60da8bb5870e37: [
      0: 25,
      1: "title 2"
    ],
    61e83b48e498cc5aae9dc741: [
      0: 22,
      1: "title 3"
    ]
  }

So far I've tried both preparing a statement like this:

const fetchQuery = "recommendations.616f65705f60da8bb5870e37.0 : 1, recommendations.61e83b48e498cc5aae9dc741.0 : 1";

const result = await videoGamesCollection.updateOne(
        { _id: ObjectId(req.body.parentId) },
        { $inc: fetchQuery }
      );

And using array filters:

const result = await videoGamesCollection.updateOne(
        { _id: ObjectId(req.body.parentId) },
        { $inc: {"recommendations.$[elem].0": 1} },
        {arrayFilters: [{"elem":{$in:[req.body.voteIds]}}]}
      );

But neither seems to work. Is this possible or is my only option converting to array of arrays instead?

Thanks!



Solution 1:[1]

You need to enclose recommendations.616f65705f60da8bb5870e37.0 in quotes, like:

const result = await videoGamesCollection.updateOne(
        { _id: ObjectId(req.body.parentId) },
        { 
          $inc: {
             "recommendations.616f65705f60da8bb5870e37.0": 1,
             "recommendations.61e83b48e498cc5aae9dc741.0": 1 
        }
      );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 qtxo