【问题标题】:MongoDB in PHP - How do I insert items into an array in a collection?PHP中的MongoDB - 如何将项目插入集合中的数组?
【发布时间】:2011-07-19 06:15:25
【问题描述】:

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

{ 
    "_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 驱动程序将另一个“任务”添加到集合中此项的“任务”数组中

【问题讨论】:

    标签: php json mongodb database nosql


    【解决方案1】:

    使用Mongo的$push操作:

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

    【讨论】:

    • 正是我想要的!谢谢。
    • 问题应该是......如何将项目添加到现有文档的数组中?插入带有数组的文档不是用 $push 完成的,因为 $push 是一个更新操作符。你知道新版本的 php MongoDB API 是如何做到这一点的吗?
    猜你喜欢
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 2022-12-17
    • 2017-07-10
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多