dongniechi7825 2016-04-04 20:56
浏览 87
已采纳

如何使用PHP将数组插入mongodb?

    update(array("loc1"=>$locations[0]),array('$set'=>(object)array("Users"=>(array("user_id"=>$user_id,"user_name"=>$Email)))));

I wrote the above code to insert user_id to the array users, after execution i got the result in mongodb shown below

    {
"_id" : ObjectId("5702cfd2c693b54008000035"),
"loc1" : "Anapara",
"loc2" : "Puthucurichy",
"loc3" : "Kadinamkulam",
"loc4" : "Kerala",
"loc5" : "India",
"Users" : {
    "user_id" : ObjectId("5702cfd2c693b54008000034"),
    "user_name" : "chunks@yahoo.com"
}

}

Here the keyword Users is not becoming an array, i mean i want it in this format (value of user in a square bracket):

    "Users" :[ {
                 "user_id" : ObjectId("5702cfd2c693b54008000034"),
                 "user_name" : "chunks@yahoo.com"}
             ]

What modification should i do in my php code to put the values in square bracket?

  • 写回答

1条回答 默认 最新

  • dtu72460 2016-04-05 09:14
    关注

    BSON array ([ ... ]) can be saved from PHP if you use an array indexed by consecutive numbers (a list). So your code needs to be (I'll allow myself to make it more readable to illustrate better):

    update(
        array("loc1" => $locations[0]),
        array('$set' => array(
             "Users"=> array( // this makes Users a list
                 array("user_id"=>$user_id,"user_name"=>$Email) // this is your embedded object
                 // here could go another embedded object separated by a comma
             )
        ))
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题