PHP中的MongoDB - 如何将项目插入集合中的数组? [英] MongoDB in PHP - How do I insert items into an array in a collection?

查看:25
本文介绍了PHP中的MongoDB - 如何将项目插入集合中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这一定很简单,但我似乎无法弄清楚...假设我有一个集合 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))
);

这篇关于PHP中的MongoDB - 如何将项目插入集合中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆