1

Considering this document :

{
    "_id" : ObjectId("54d0a5cdc9311cad167f55d5"),
    "Title" : "Add Solaris Zone",
    "Type" : "System",
    "Tasks" : [
            {
                    "TaskName" : "Ask for an IP",
                    "TaskDescription" : "Ask to network team for an ip adress",
                    "Custom" : [
                            {
                                    "id" : ObjectId("54d0a5cdc9311cad167f55d3"),
                                    "name" : "ip",
                                    "value" : ""
                            },
                            {
                                    "id" : ObjectId("54d0a5cdc9311cad167f55d4"),
                                    "name" : "vlan",
                                    "value" : ""
                            }
                    ],
                    "Prerequisites" : [ ]
            }

}

Is it possible to update the property "value" of, let's say field ip, for task where taksname = "Ask for an IP" ?

I'm able to update properties one level higher (like TaskName) but what if the embedded document contains an array of embedded documents ?

1 Answers1

0

Usually to update fields in nested arrays you can use $ operator. http://docs.mongodb.org/manual/reference/operator/update/positional/

However, since it can be used only once, you cannot update array elements nested inside the neasted array.

What you could do however (assuming you know what the position of "task" element is) is to specify position like:

update({...}, { $set: {"Tasks.0.Custom.$.value": "MyVal"}})
marcinn
  • 1,786
  • 11
  • 13
  • Hi, thanks for the answer, I don't know the position of task element so what should i do : 1) load the whole Task element in my app, edit it and write it back to mongo, 2) do a first query to get the position of tasks (if it's possible) 3) change the design of my database (however i don't think it's bad) – Christophe De Loeul Feb 03 '15 at 11:35
  • Second option is not so good since someone can edit the element between your read and update - so you would update wrong element. I would go with either first or third option both are good. If it makes sense for task to live outside main element - then 3rd option seems good. If you load whole aggregate in your application and work with it - 1st one is the way to go – marcinn Feb 03 '15 at 12:00
  • I think it's a non sense in my case to get the task out of the main document, so i'll read the whole document, update it in my app and write it back. Thanks. – Christophe De Loeul Feb 03 '15 at 13:09