MongoDB update an object inside an array inside an array

I’m trying to update the quantity on a field from an object in an array nested in an array. And I can’t figure the query to do it.

I can update a field in an object inside one array. But when I try to go one level down I get a “too many $ in the query”

this is the document. How to increase the quantity of the red wine item from 3 to 5?

{
    "_id" : "bTTALd6kuBfEqFEiW",
    "charges" : [ 
        {
            "_id" : "0",
            "type" : "charge",
            "selected" : "tab-unselected",
            "concept" : "booking",
            "items" : [ 
                {
                    "_id" : "rGmt5wLuLN6MyW3og",
                    "item" : "red Wine",
                    "quantity" : 3,
                    "price" : 280
                },
{
                    "_id" : "6MyW3orGmt5gwLuLN",
                    "item" : "white Wine",
                    "quantity" : 3,
                    "price" : 280
                }
            ]
        }
    ]
}

Hi,

You can use arrayFilters to update nested arrays.

Something like this should work.

YOUR_COLLECTION.rawCollection().update(
 {
  id: "bTTALd6kuBfEqFEiW",
 },
 {
  $set: { 'charges.$[outer].items.$[inner].quantity': 5},
 },
 {
  arrayFilters: [{ 'outer.id': "0"}, { 'inner.id': "rGmt5wLuLN6MyW3og" }],
 }
);
2 Likes

@zayco

Thank you it has worked like a charm.