Update an array within an array

Spinning my wheels trying to get this update to work:

db.accounts.updateMany(
  {"members.items": {$exists:1}}, 
  {$set:{"members.items.$[elem].key": "123"}},
  {arrayFilters:[
    {"elem.key":"789"}
  ]}
)

Gives the error members.items must exist in order to apply array updates.

My account object has an array of member objects and members have an array of item objects

Hello @Jeff_VanHorn,

It would be helpful if you show an example document,

I assume the document you have,

  {
    "members": [
      {
        items: [
          { key: "789" }
        ]
      },
      {
        otherKey: 1
      }
    ]
  }

Your query would be,

  • check the key in the match part
  • check items exists a condition in array filters and put in your update part
db.accounts.updateMany(
  { "members.items.key": "789" },
  {
    $set: {
      "members.$[m].items.$[elem].key": "123"
    }
  },
  {
    arrayFilters: [
      { "m.items": { $exists: true } },
      { "elem.key": "789" }
    ]
  }
)
1 Like

That nailed it, thanks.

Makes sense now that I see it.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.