Updating field in nested documents in mongodb php -


i use mongodb php driver, convenience write query syntax, find more elegant solution found today following problem.

i have collection "story" nested document:

collection story:

{      "_id":"story1",    "title":null,    "slug":null,    "sections":[         {            "id_section":"s1",          "index":0,          "type":"0",          "elements":[               {                  "id_element":"001",                "text":"img",                "layout":1             }          ]       },       {            "id_section":"s2",          "index":0,          "type":"0",          "elements":[               {                  "id_element":"001",                "text":"hello world",                "layout":1             },             {                  "id_element":"002",                "text":"default text",                "layout":1             },             {                  "id_element":"003",                "text":"hello world 3",                "layout":"2"             }          ]       }    ] } 

assuming want change value of element id_element => 002 present in section id_section => s2 of story _id => story1

the solution i've found find "position" of element 002 , following

1]

$r=$m->db->plot->findone(array("_id" => 'story1',                                         "sections.id_section"=>'s2'),                                         array('_id'=>false,'sections.$.elements'=>true)); 

2]

foreach($r['sections'][0]['elements'] $key=>$value){     if($value['id_element']=='002'){         $position=$key;         break;     } 

3]

$m->db->story->update(array('_id'=>'story1','sections.id_section'=>'s2','sections.elements.id_element'=>'002'),                 array('$set'=>array('sections.$.elements.'.$position.'.text'=>'new text')),                 array('w'=>1)); 

i repeat not think elegant solution, , noticed common problem.

thank s.

you can't use $ match multiple levels of nested arrays. why it's not idea nest arrays in mongodb if anticipate searching on properties anywhere deeper top level array. alternatives fixed document structure know positions in 1 of arrays want update @ (or retrieve document , find out indexes, doing) or retrieve document, update in client, , reinsert it.

the other option rethink how data modeled documents in mongodb nested arrays don't happen/ in case, story collection of sections collections of elements. instead of making story document, have story represented multiple section documents. section documents share common field value indicate belong same story. above update possible update on 1 section document using $ positional operator match , update correct element.


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -