Updating a nested object in a document using mongoose

MongoDB supports the single-level deep update of subdocument using positional operator ($).

db.collection_name.update({
    _id: ObjectId("61da0ab855483312e8f4483b"),
    "products.productCode": "4pf"
},
{
    "$set": {
        "products.$.productName": "twitteroauth name updated"
    }
})

In the above update clause, $ will be replaced by the matching index of a subdocument at a runtime.

For example $ will be replaced by value 1 at a runtime because of "products.productCode": "4pf" condition

Please note the below points:

  1. You must include the array field as part of the query document.
  2. The positional operator cannot be used for updates inside of a nested array.

Additional Reference: https://docs.mongodb.com/manual/reference/operator/update/positional/