php - Update document doesnt work right -
i using code below update mongodb document:
foreach($jarray $value){ $tablename = $value['tablename']; $ean = $value["ean"]; $amount= $value["amount"]; $new_data = array( '$set' => array( 'inventar' => array( array ( 'ean' => $ean, 'amount' => $amount ) ) ) ); $collection->update(array("tablename"=>$tablename), $new_data); $response["update"] = 1; echo json_encode($response); }
the database looks executing code this:
{ "_id": { "$id": "557daa73d8291bc6268b4578" }, "inventar": [ { "ean": "802.6180.222", "amount": "0" } ], "out_date": "15.05.2015", "out_email": "email@email.com", "out_user": "pb", "tablename": "dd_aa" }
but inventar-part should contain more values.
the json send is:
[{"amount":"0","ean":"802.0079.127","tablename":"dd_aa"},{"amount":"40","ean":"802.6180.222","tablename":"dd_aa"}]
why second ean forgotten , not updated? structure right?
thank you
why second ean forgotten [...] ?
as suggested @gypsycoder in comment, using $push
solve issue.
the reason $set
create or replace field. but, $push
create array field if not exists, , append item @ end of array.
so, given example, correct code should this:
$new_data = array( '$push' => array( 'inventar' => array( 'ean' => $ean, 'amount' => $amount ) ) ); $collection->update(array("tablename"=>$tablename), $new_data);
please note, default $push
push 1 item @ time. so, must not wrap item push in array. if need push several items part of same update statement, need wrap elements in array, passed argument $each
modifier.
Comments
Post a Comment