1

I want to update all documents in my collection that have a specific value that resides inside a nested array that is structured like this:

[{
  "_id": "1",
  "arrayX": [
    {
      "id2": "123", 
      "arrayY": [
        {
          "colour": "blue",
          "size": "small"
        },
        {
          "colour": "red",
          "size": "small"
        },
      ]
    },
    {
      "id2": "12345", 
      "arrayY": [
        {
          "colour": "blue",
          "size": "small"
        },
        {
          "colour": "purple",
          "size": "small"
        },
      ]
    }
  ]
}]

In this case, I need to update the value "blue" to "white" in the 2 elements that are presented in the example above.

I came up with something like this but it's not working:

db.collection.update(
   { arrayX.$.arrayY.$.colour: "blue" },
   { $set: { "arrayX.$.arrayY.$.colour" : "white" } },
   { upsert: false }
)

Thanks in advance

1

1 Answer 1

1

Try arrayFilters, to update specific element in nested array and $[] to update all elements,

db.collection.updateMany(
  { "arrayX.arrayY.colour": "blue" },
  {
    $set: {
      "arrayX.$[].arrayY.$[c].colour": "white"
    }
  },
  {
    arrayFilters: [
      { "c.colour": "blue" }
    ]
  }
)

Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.