Update an old value "V1" in an array to the new value "V11" using Mongo Query

Viewed 36

I have the data structure as follows:

{
    "metadata" : {
        "custom_metadata" : [
            {
                "key_id" : "6052e700dc84ef7d492b5d30",
                "type" : "freetext",
                "value" : [
                    "desh",
                    "Fauji"
                ]
            }
        ],
        "tag_ids" : [ ],
        "category_id" : "5a02e20a23dfee730bbd7f4f",
    }
}

I want to achieve updating a specific value inside the "value" array here (without knowing its index) using db.update() query. Example: I want to update the above doc to :

{
    "metadata" : {
        "custom_metadata" : [
            {
                "key_id" : "6052e700dc84ef7d492b5d30",
                "type" : "freetext",
                "value" : [
                    "Desh ki Dharti",
                    "Fauji"
                ]
            }
        ],
        "tag_ids" : [ ],
        "category_id" : "5a02e20a23dfee730bbd7f4f",
    }
}
1 Answers

Demo - https://mongoplayground.net/p/EypYAuHQTh3

Use $[]

The filtered positional operator $[] identifies the array elements that match the arrayFilters conditions for an update

db.collection.update({},
    { $set: { "metadata.custom_metadata.$[].value.$[value]": "Desh ki Dharti" }},
    { arrayFilters: [ { "value": "desh" } ]}
)

Update

Demo - https://mongoplayground.net/p/OCUyZXE8Dse

db.collection.update(
  { "metadata.custom_metadata.value": "desh" }, // query to find matching documents where value is "desh"
  { $set: { "metadata.custom_metadata.$[].value.$[v]": "Desh ki Dharti" } },
  { arrayFilters: [ { "v": "desh" } ]}
)
Related