使用php将新的内部对象插入现有对象mongodb [英] insert new inner object into existing object mongodb using php

查看:70
本文介绍了使用php将新的内部对象插入现有对象mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的mongo收藏集中有以下文档

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);

但是当我运行这段代码时,它通过插入新的(第三个用户)对象来更新Friends对象,并删除旧的对象(avi12和第二个对象),只有最后一个在扩孔.

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.

如何将新对象插入到Friends对象中,以保留先前的数据,我也不想使用数组.请帮忙...

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

推荐答案

当您要在现有数组中推送新对象时,需要使用$push而不是$set.

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

这篇关于使用php将新的内部对象插入现有对象mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆