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

报告相同问题?