2011-03-20 101 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

相關問題