PHP中的MongoDB - 如何将项目插入集合中的数组?

2022-01-13 00:00:00 json mongodb database nosql php

这一定很简单,但我似乎无法弄清楚...假设我有一个集合 users,这是集合中的第一项:

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"
    }
] }

然后我将如何使用 MongoDB 的 PHP 驱动程序将另一个任务"添加到集合中此项的任务"数组中

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

推荐答案

使用Mongo的$push操作:

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

相关文章