1
[
  {
    "id": 1,
    "items": [
      {
        id: 15,
        score: 10
      },
      {
        id: 14,
        score: 100
      },
      {
        id: 12,
        score: 1
      }
    ]
  },
  {
    "id": 2,
    "items": []
  }
]

Now, I try to update items whose id is 14,15 & used the following query.

db.collection.update({
  "items.id": {
    $in: [
      14,
      15
    ]
  }
},
{
  $set: {
    "items.$.score": 444
  }
},
{
  multi: true
}
)

but it updated only the first match in items that is that is id with 15, what can be wrong?

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "id": 1,
    "items": [
      {
        "id": 15,
        "score": 444
      },
      {
        "id": 14,
        "score": 100
      },
      {
        "id": 12,
        "score": 1
      }
    ]
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "id": 2,
    "items": []
  }
]
notnotundefined
  • 3,493
  • 3
  • 30
  • 39
  • Does this answer your question? [MongoDB update multiple subdocuments with or query](https://stackoverflow.com/questions/40904007/mongodb-update-multiple-subdocuments-with-or-query) – turivishal Mar 16 '21 at 15:16

2 Answers2

2

You can do it with Positional identifiers $[]

db.collection.update({
  "items.id": {
    $in: [
      14,
      15
    ]
  }
},
{
  $set: {
    "items.$[element].score": 444
  }
},
{
  arrayFilters: [
    {
      "element.id": {
        $in: [
          14,
          15
        ]
      }
    }
  ],
  multi: true
})

try it here

AlexisG
  • 2,476
  • 3
  • 11
  • 25
2

Use arrayFilters with targeted array elements: here is the doc

db.collection.update({
  "id": 1
},
{
  "$set": {
    "items.$[ele].score": 20
  }
},
{
  arrayFilters: [
    {
      "ele.id": {
        "$in": [
          15,
          14
        ]
      }
    }
  ]
})

see play ground code https://mongoplayground.net/p/cdgu1aqLwsI

John
  • 2,633
  • 4
  • 19
  • 34