How to find and update the nested object in mongodb

Viewed 20

enter image description here

How to find and update the nested object in MongoDB? I am trying but not working. Listen this in one document only of specific category. Fist I need to find a particular category then update the product stock.

 await db.collection("protablekeyboards").findOneAndUpdate({ 'category': "portable_keyboards", "products.sku": sku}).project({ products: 1 }).toArray()
1 Answers

You can use $[identifier] and arrayFilters.

For Example :

db.collection.update({
  "_id": 1
},
{
  $set: {
    "products.$[elem].product_stock": 10
  }
},
{
  arrayFilters: [
    {
      "elem.sku": "sku_1"
    }
  ]
})

Here with the first, I match only the documents where "_id": 1

With the update query, I change the value of the product_stock variable in products to 10. But it only change the items of the array that match the arrayFilters condition. Witch is where the skuis equal to "sku_1"

try it here

Related