3

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},
            ]
        }
    ]
}
vladtax
  • 203
  • 1
  • 2
  • 9

1 Answers1

6

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.

Philipp
  • 67,764
  • 9
  • 118
  • 153
  • I am ok with a bit more work, it is not a requirement to have a single query, can you help me with complete answer? – vladtax Sep 07 '15 at 18:58
  • 1
    @vladtax For that you would need to tell me which programming language your application is written in and hope that it's a language I am at least a bit familiar with. – Philipp Sep 07 '15 at 19:47