Search code examples
mongodbmongoosemongodb-query

Mongoose Update Nested Array Object


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


Solution

  • 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" }] }
    )