I ve the following content in mongo db collection,
{ "_id" : ObjectId("5052f343381ef8bc10000011"), "first_name" : "Tadataka", "midle_name" :
"", "last_name" : "Yamada", "title" : "Independent Director", "biogra
phy" : "Dr. Tadataka Yamada, M.D., is Independent Director of Agilent Technologi
es Inc., ", "rank" : " ", "department" : " ", "current" : "true", "company_id" : ObjectId("50072714b4a6deba100051d3"
) } }
When I tried to update the above content for few fields and also insert new field if not exist, the existing fields get over written. Here is my code,
$mycollection->update(array("_id" => $id), array('$set' => array("first_name" => $first_name, "updated_at" => $uat));
and the result I am getting is
{ "_id" : ObjectId("5052f343381ef8bc10000011"), "first_name" : "Tadataka", "updated_at" : 134567894 }
Instead of updating just the values, my whole content gets overwritten, where I am missing.?
The
update()in the code you shared is correct. Since you’re using an atomic modifier,$set, there is no reason that the entire document for the given_idwould be overwritten. The following script easily reproduces this, and outputs the example document with itsfirst_namefield altered andupdated_atfield added:If you run this locally, you should see:
It would probably be helpful if you shared how you obtained the last result you pasted, but your update query certainly isn’t to blame here.
As a side note, you likely want to use a proper boolean value for the
currentfield in your document instead of the string"true".