2011-03-20 97 views
3

这必须是容易的,但我似乎无法推测出来......让说我有一个收集users,这是集合中的第一项:PHP中的MongoDB - 如何将项目插入到集合中的数组中?

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

如何与PHP驱动程序MongoDB的将我然后去并添加另一个“任务”的“任务”数组中此项目集合中

回答

12

使用蒙戈的$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)) 
); 
+0

正是我要找的!谢谢。 – 2011-08-01 01:33:11

+0

问题应该是......如何将项目添加到现有文档中的数组?用数组插入文档不是用$ push完成的,因为$ push是更新操作符。你知道这是怎么用新版本的php MongoDB API完成的吗? – pitchblack408 2016-03-01 18:41:29

相关问题