Search code examples
phpmongodbupdatingmultidimensional-array

mongodb updating nested array in a document using PHP


document structure example is:

{
   "dob": "12-13-2001",
   "name": "Kam",

   "visits": {
     "0": {
       "service_date": "12-5-2011",
       "payment": "40",
       "chk_number": "1234455",  
    },
     "1": {
       "service_date": "12-15-2011",
       "payment": "45",
       "chk_number": "3461234",  
    },
     "2": {
       "service_date": "12-25-2011",
       "payment": "25",
       "chk_number": "9821234",  
    } 
  } 
}

i am trying to update only "payment" in visit - 2 and chk_number in visit - 1 using following:


$query_criteria =  array("name" => "Kam", "dob" => "12-13-2001");

$updated_data = array();

$updated_data['visits'][1]['chk_number'] = 567;
$updated_data['visits'][2]['payment'] = 100;

$ret = $collection->update( $query_criteria, array('$set' => $updated_data), array("safe" => true) );

But this update deletes all the visits and overwrite them with vists containing only payment and chk_number .

I am new to mongodb and PHP. Can anyone please point me towards what wrong am i doing and how to fix this problem.

Many thanks in advance........


Solution

  • You should use a dot notation.

    db.collection.update(query_criteria, 
                         {$set: {'visit.2.payment': 100, 
                                 'visit.1.chk_number': 567}});
    

    What you're doing is this:

    db.collection.update(query_criteria, 
                         {'visit' : {'2' : {'payment': 100}}, 
                                    {'1': {'chk_number': 567}}});
    

    And it basically means "find a document and overwrite it with this new one".

    The code I wrote are in Javascript (as they would appear in mongo shell). I leave it up to you to translate to proper PHP (I'm not a PHP guy).