Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update double nested array mongodb

I have the below document which contains double nested array format. I have to update the "level" field to "Senior Engineer" when the "someKey":"somevalue" and "Company":"Company1" and "Name":"Nandhi".

Document

    { 
        "_id" : "777", 
        "someKey" : "someValue", 
        "someArray" : [
            {
                "Company" : "Company1", 
                "someNestedArray" : [
                    {
                        "name" : "Nandhi", 
                        "level" : "Junior Engineer"
                    }, 
                    {
                        "name" : "Rajan", 
                        "level" : "Senio Engineer"
                    }
                ]
            }], 
            {
                "Company" : "Company2", 
                "someNestedArray" : [
                    {
                        "name" : "Nandhi", 
                        "level" : "Junior Engineer"
                    }, 
                    {
                        "name" : "Rajan", 
                        "level" : "Senio Engineer"
                    }
                ]
            }
        ]
    }

Update Query I tried

    db.Test123.updateOne(
    {"someKey" : "someValue","someArray.Company":"Company1"},
    {$set:{"someArray.$[someNestedArray].level":"Senior Developer"}},
    {arrayFilters:[{"someNestedArray.name":"Nandhi"}]}
    );

Output Screenshot

enter image description here

As you can seen that, the modifiedCount returns 0. Please advice on this!

like image 634
Nandy Avatar asked Mar 31 '26 00:03

Nandy


1 Answers

You need to define arrayFilter for every level of nesting, try:

db.Test123.update(
    { "someKey" : "someValue" },
    { "$set": { "someArray.$[someArrayDoc].someNestedArray.$[someNestedArrayDoc].level": "Senior Developer" } },
    { arrayFilters: [ {"someArrayDoc.Company": "Company1"}, { "someNestedArrayDoc.name": "Nandhi" } ] }
)
like image 56
mickl Avatar answered Apr 02 '26 11:04

mickl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!