Search code examples
mongodbmongoose

update value of an object in two nested array of objects


This is a short summary of the schema of the Products collection:

{   
    id,
    variations: [{
        id,
        lots: [{
            quantity,
            size
        }]
    }] 
}

I need to modify the quantity of a single lot based on the: product.id, variation.id and lot.size.

How can I do that?

I tried with this code but it didn't edit any field of the entire collection

Product.updateOne(
      {
        _id: variation.productId,
        "variations._id": variation.variationId,
        "variations.lots.size": variation.size,
      },
      { $inc: { "variations.lots.$.quantity": -variation.quantity } }
    );

Solution

  • You should use the arrayFilters feature in MongoDB updateOne operation.

    From the docs:

    Optional. An array of filter documents that determine which array elements to modify for an update operation on an array field. In the update document, use the $[] filtered positional operator to define an identifier, which you then reference in the array filter documents. You cannot have an array filter document for an identifier if the identifier is not included in the update document.

    Here is a final working query:

    db.collection.update({
      "_id": "p001"
    },
    {
      $inc: {
        "variations.$[v].lots.$[l].quantity": -1
      }
    },
    {
      arrayFilters: [
        {
          "v.id": "v002"
        },
        {
          "l.size": "S"
        },
        
      ]
    })
    

    And here is a link to MongoDB playground to see this query work: https://mongoplayground.net/p/UAz_Hmg0Z5t