Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep update of Mongo DB document

I have the following document structure in Mongo DB 3.0 document:

{
    id: "ID",
    name: "NAME",
    items:[
        {
            id:"100",
            name:"Item Name",
            fields:[
                {a:"field 1", b:44},
                {a:"field 2", b:56},
            ]
        }
    ]
}

I need to update "field 2" to value of 72, so that the result will be as follow:

{
    id: "ID",
    name: "NAME",
    items:[
        {
            id:"100",
            name:"Item Name",
            fields:[
                {a:"field 1", b:44},
                {a:"field 2", b:72},
            ]
        }
    ]
}
like image 722
vladtax Avatar asked Nov 20 '25 05:11

vladtax


1 Answers

Unfortunately you stumbled upon a very annoying limitation of MongoDB.

You can update individual array entries with the $ placeholder. But unfortunately you can only have one of these in a field-name. That means arrays-within-arrays can not be updated with a single query.

A possible workaround is to use a find to request a copy of the whole items.$.fields array, edit it on the application layer, and then do an update which replaces the whole array.

There is an open ticket on the official bugtracker about this issue which has "major" priority. But the ticket exists since 2010, so I wouldn't hold me breath.

like image 110
Philipp Avatar answered Nov 21 '25 23:11

Philipp



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!