Update deep nested array

Hello. I’ve some documents in a collection deep nested
Example

 {
  _id: ObjectId("..."),
  data: [
    {
      systemNumber: "ABCD",
      logs: [
        {
          identifierLog: "Blue",
          level: 10,
        },
        { identifierLog: "Red", level: 4 },
      ],
    },
    {
      systemNumber: "ZXY",
      logs: [
        {
          identifierLog: "Purple",
          level: 2,
        },
        { identifierLog: "Yellow", level: 9 },
      ],
    },
  ],
};

I need to update the level based on the identifierLog, I’ve tried many things but this is the one that gets the closest.

model.updateOne( {data.logs.identifierLog: 'Red'}, { "$set":  { data.$.logs.$[].level: 2 } }      )

The problem with this solution is that all the elements in the array get updated to level 2 so I end with this

      logs: [
        {
          identifierLog: "Blue",
          level: 2,
        },
        { identifierLog: "Red", level: 2 },
      ],

Thanks in advance.

Solved it!

model.updateOne( {data.logs.identifierLog: 'Red'}, { "$set":  { data.$.logs.$[log].level: 2 } }, {arrayFilters: [{"log.identifierLog": 'Red'}]}      )

Not sure if there are better options but this one works good

1 Like

Hi, i’m having trubles with a similar problem, i found your solution but i want to ask just one question to you, in: { data.$.logs.$[log].level is there a variable index in $[log] or it is a hardcoded ?