insert new inner object into existing object mongodb using php

南笙酒味 提交于 2019-12-11 16:07:49

问题


I have the following document in my mongo collection

{"_id":"5a9e97557cf28c1c2d00003d",
"user_id":"avi12",
"name":"Avinash",
"Friends":{
"avi12":{
"From":"avi12",
"To":"chandu",
"Friend_status":"pending",
"Time":1520342869,
"requestid":"s_avi12_first"
},
"second_user":{
"From":"avi122",
"To":"chandu2",
"Friend_status":"pending2",
"Time":1520342869,
"requestid":"2s_avi12_first"
}
}
}

I want to inset new object ("Third user") into Friends object. I have tried the following code...

$update_friend_send=array(
                        $user_name=>array(
                            "From"=>$user_name,
                            "To"=>$To,
                            "Friend_status"=>"pending",
                            "Time"=>time(),
                            "requestid"=>"s_".$user_name."_".$sender_id
                            ));


                    $condition = array("_id"=>$realmongoid);
                    $data = array('$set' => array('Friends.$' =>$update_friend_send));

                    $collection->update($condition,$data);

but when I run this code, it is updating the Friends object by inserting new (third user) object and removes old objects(avi12 and second), only last one is reaming.

How I can insert new object into Friends object keeping the previous data, also I don't want to use array. please help...


回答1:


You need to use $push instead of $set when you want to push new object in existing array.



来源:https://stackoverflow.com/questions/49132253/insert-new-inner-object-into-existing-object-mongodb-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!