Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading