1

I have a MongoDB collection as follows

 [
  {
    actions: [
      {
        _id : ObjectId('641b34b7aa7f4269de24f050')
        participants: [
          {
            _id : ObjectId('641b33c3aa7f4269de24ef10')
            referenceId: "641b3414aa7f4269de24efa5",
            name: "Person one",
            email: "example@gmail.com"
          },
          {
            _id : ObjectId('61bb9105362e810ae9a6826f')
            referenceId: "641b3414aa7f4269de24ef4g",
            name: "Person two",
            email: "example2@gmail.com"
          }
        ]
      }
    ]
  }
]

I want to update participants' name by filtering participants' referenceId.

As an example, I want to update the document where referenceId = 641b3414aa7f4269de24efa5 and then update the name to "Person 1".Then the document will look like this after update

[
  {
    actions: [
      {
        _id : ObjectId('641b34b7aa7f4269de24f050')
        participants: [
          {
            _id : ObjectId('641b33c3aa7f4269de24ef10')
            referenceId: "641b3414aa7f4269de24efa5",
            name: "Person 1",
            email: "example@gmail.com"
          },
          {
            _id : ObjectId('61bb9105362e810ae9a6826f')
            referenceId: "641b3414aa7f4269de24ef4g",
            name: "Person two",
            email: "example2@gmail.com"
          }
        ]
      }
    ]
  }
]

Is there any way that I can perform this

Susampath
  • 706
  • 10
  • 13
  • Does this answer your question? [Update array element by id with mongo query](https://stackoverflow.com/questions/20262405/update-array-element-by-id-with-mongo-query) – ray Mar 28 '23 at 18:58
  • @ray Nope. I was confused with the update object inside the nested array. Your example has only one array.Not a nested one – Susampath Mar 28 '23 at 19:02

1 Answers1

1

almost similar to this
you can use arrayFilters option to specify which elements to modify in an array field

filtered positional operator $[<identifier>] is used to identify the array elements that match the arrayFilters conditions for the update operation. In this example the first action and in that the first participant ( referenceId 641b3414aa7f4269de24efa5)

db.collection.update(
  { "actions.participants.referenceId": "641b3414aa7f4269de24efa5" },
  { $set: { "actions.$[action].participants.$[participant].name": "Person 1" } },
  { arrayFilters: [{ "action.participants.referenceId": "641b3414aa7f4269de24efa5" }, { "participant.referenceId": "641b3414aa7f4269de24efa5" }] }
)

playground

EDIT in this example even this works

db.collection.update(
  {},
  { $set: { "actions.$[action].participants.$[participant].name": "Person 1" } },
  { arrayFilters: [{ "action.participants.referenceId": "641b3414aa7f4269de24efa5" }, { "participant.referenceId": "641b3414aa7f4269de24efa5" }] }
)
cmgchess
  • 7,996
  • 37
  • 44
  • 62