0

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 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

1 Comment

For $push it must be an array and i don't want to use array, i want nested objects... for push command mongo command showing the following error "The field 'Friends' must be an array but is of type object in document"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.