insert new inner object into existing object mongo

2019-08-22 01:12发布

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条回答
冷血范
2楼-- · 2019-08-22 01:31

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

查看更多
登录 后发表回答