MongoDB in PHP - How do I insert items into an array in a collection?

假装没事ソ 提交于 2021-02-15 11:58:13

问题


This has to be easy, but i can't seem to figure it out... Let say i had a collection users and this is the first item in the collection:

{ 
    "_id" : ObjectId("4d8653c027d02a6437bc89ca"), 
    "name" : "Oscar Godson", 
    "email" : "oscargodson@xxx.com", 
    "password" : "xxxxxx", 
    "tasks" : [
    {
        "task" : "pick up stuff",
        "comment" : "the one stuff over there"
    },
    {
        "task" : "do more stuff",
        "comment" : "lots and lots of stuff"
    }
] }

How with the PHP driver for MongoDB would I then go and add another "task" to the "tasks" array in this item in a collection


回答1:


Use Mongo's $push operation:

$new_task = array(
  "task" => "do even more stuff",
  "comment" => "this is the new task added"
);
$collection->update(
  array("_id" => ObjectId("4d8653c027d02a6437bc89ca")), 
  array('$push' => array("tasks" => $new_task))
);


来源:https://stackoverflow.com/questions/5370925/mongodb-in-php-how-do-i-insert-items-into-an-array-in-a-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!