2013-05-18 56 views
0

我想用PHP學習MongoDB。我可以使用 - > save($ object)成功保存一個新文檔。我的目標是將子文檔添加到具有特定_id的文檔中。PHP/MongoDB - 用_id將文檔添加到文檔

我有一個文件:

"5197f4bef045a1d710000032": { 
"_id": { 
    "$id": "5197f4bef045a1d710000032" 
}, 
"tag": 5487, 
"serial": "1z5589ss56", 
"type": "Soda Can", 
"dept": "NOC", 
"location": "Mitchell", 
"date": 1368913086, 
"moves": null 
} 

我想插入一個新的文檔到「動作」。

我已經能夠使用$ set一次,但是後續的$ push什麼都不做。

<?php 


$m = new Mongo(); 

$d = $m->selectDB('peeps'); 
$c = $d->family; 
$fields = array('tag' => 5487 , 'serial' => '1z5589ss56', 'type' => 'Soda Can', 'dept' => 'NOC', 'location' => 'Mitchell', 'date' => time()); 

$can = new Asset($fields); 
#$c->save($can); 

#Update to insert move 

$c->update(array('_id' => new MongoID('5197f0cef045a1d710000032')), array('$push' => array('moves' => $can))); 


$cur = $c->find(); 
$J = json_encode(iterator_to_array($cur)); 
print($J); 


class Asset{ 

    public $tag; 
    public $serial; 
    public $type; 
    public $dept; 
    public $location; 
    public $date; 
    public $moves; 

    public function __construct($fields){ 
     $this->tag = $fields['tag']; 
     $this->serial = $fields['serial']; 
     $this->type = $fields['type']; 
     $this->dept = $fields['dept']; 
     $this->location = $fields['location']; 
     $this->date = $fields['date']; 
    } 
} 

基於我已閱讀,這應該創建一個嵌套的文檔中5197f0cef045a1d710000032.moves每次我重新加載頁面的時間。

我不知道我錯過了什麼。

感謝,

米切爾

回答

2

你不應該使用$用一個簡單的值設置,如果你打算在以後使用$push相同的字段。

第一次更新時也使用$push。它將創建一個單個元素的數組,然後您將能夠向其添加(推送)更多元素。

+0

謝謝你,我不知道爲什麼我無法在森林中找到樹。 :) – xandout