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
             )
        ))
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?