1

I have a MongoDB collection as follows

 [
  {
    actions: [
      {
        _id : ObjectId('641b34b7aa7f4269de24f050')
        participants: [
          {
            _id : ObjectId('641b33c3aa7f4269de24ef10')
            referenceId: "641b3414aa7f4269de24efa5",
            name: "Person one",
            email: "[email protected]"
          },
          {
            _id : ObjectId('61bb9105362e810ae9a6826f')
            referenceId: "641b3414aa7f4269de24ef4g",
            name: "Person two",
            email: "[email protected]"
          }
        ]
      }
    ]
  }
]

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: "[email protected]"
          },
          {
            _id : ObjectId('61bb9105362e810ae9a6826f')
            referenceId: "641b3414aa7f4269de24ef4g",
            name: "Person two",
            email: "[email protected]"
          }
        ]
      }
    ]
  }
]

Is there any way that I can perform this

2
  • Does this answer your question? Update array element by id with mongo query Commented Mar 28, 2023 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 Commented Mar 28, 2023 at 19:02

1 Answer 1

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" }] }
)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.