Update every sub document in sub sub array

Hi there, I want to update every sub-element in sub of sub-array
This is my Schema:

{
  "items": [
    {
      "product": "63c66986e9e1ab5801914215"
      "variant": "63c66986e9e1ab5801914216",
      "locations": [
        {
          "quantity": 1,
          "location": "63c66733e3e9f11b2e8f8947"
        }
      ],
    },
    {
      "product": "63c66776a6d77f32e2776c63",
      "variant": null,
      "locations": [
        {
          "quantity": 6,
          "location": "63c66733e3e9f11b2e8f8947",
        },
        {
          "quantity": 7,
          "location": "63c66733e3e9f11b2e8f8948",
        }
      ]
    }
  ],
  "paymentStatus": "PAID",
  "fulfilledStatus": "PARTIALLY-FULFILLED",
  "orderId": "O-001",
}

So here I want to add a new field “fulfilledStatus” in the locations array for every item in the items array that got the location = “63c66733e3e9f11b2e8f8947”

so the items should like this after update

  "items": [
    {
      "product": "63c66986e9e1ab5801914215"
      "variant": "63c66986e9e1ab5801914216",
      "locations": [
        {
          "quantity": 1,
          "location": "63c66733e3e9f11b2e8f8947",
          "fulfilledStatus": "FULFILLED"
        }
      ],
    },
    {
      "product": {
        "63c66776a6d77f32e2776c63"
      },
      "variant": null,
      "locations": [
        {
          "quantity": 6,
          "location": "63c66733e3e9f11b2e8f8947",
          "fulfilledStatus": "FULFILLED"
        },
        {
          "quantity": 7,
          "location": "63c66733e3e9f11b2e8f8948",
        }
      ]
    }
  ]

How can i do that

It looks like what you want to do is

2 Likes

Hello @med_amine_fh ,

I believe @steevej’s answer is correct. To expand a little, you can try below query and update it according to your requirements

db.collection.updateOne(
    {"items.locations.location" :  "63c66733e3e9f11b2e8f8947"},
    {$set: {
        'items.$[].locations.$[x].fulfilledStatus': "FULFILLED"
    }},
    {arrayFilters: [
        {"x.location": "63c66733e3e9f11b2e8f8947"}
    ]}
)

Below is the explanation of the query.

  • db.collection.updateOne() : Updates a single document within the collection based on the filter.
  • The $set operator replaces the value of a field with the specified value.
  • The filtered positional operator $[<identifier>] identifies the array elements that match the arrayFilters conditions for an update operation. In the example above, it was used in conjunction with the arrayFilters option to update all elements that match the arrayFilters conditions.
    For more details, please see Update Nested Arrays in Conjunction with $

Let me know if you have any more questions. Happy to help! :slight_smile:

Regards,
Tarun

3 Likes

Thanks for help @steevej and @Tarun_Gaur

2 Likes

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