2013-08-25 91 views
1

我嘗試使用文檔ID更新Mongodb gridfs中的文檔。最初我的文檔是:無法使用php更新Mongodb gridfs

{ 
    [_id] => MongoId Object (
      [$id] => 5218a723db8af6920a3c6624 
    ) 
    [Username] => 'Old Name' 
    [Phone]  => 'xxxxxxxxxx' 
    [Address] => 'User address' 
    [Email]  => 'User email' 
    [DecMak]  => 'Some text' 
    [Descr]  => 'my description' 
    [ImgName] => 'Image Name' 
    [Str]  => 6 
    [Date]  => '25-08-2013' 
    [filename] => 'MyJpg.JPG' 
    [uploadDate] => MongoDate Object (
     [sec] => 1377305640 
     [usec] => 262000 
    ) 
    [length]  => 1099792 
    [chunkSize] => 262144 
    [md5]  => 2e3bc10f7deeb0334ea0af4bd0fe9bdf 
} 

而我想只更新'用戶名'字段的值。我用下面的代碼更新:

$m = new MongoClient(); 
$db = $m->mydb; 
$gridfs = $db->getGridFS(); 
$collection = $db->fs->files; 
$cursor = $collection->find(array('_id'=>new MongoID($_POST['_id']))); 
    foreach ($cursor as $obj) 
    { 
    $db->fs->files->update(array('_id'=>new MongoID($_POST['_id'])), 
    //identified the document with the ID. 
    array('Username' => $_POST['name'])); 
    //Original name be changed to what filled in the webform. 
    } 

但更新後怎麼到我的文檔所做的是這樣的:

{ 
    [_id]  => MongoId Object (
     [$id] => 5218a723db8af6920a3c6624 
    ), 
    [Username] => 'New Name', 
} 

因此,所有其他鍵和值消失了 - 這是怎麼回事在我的代碼? 更新文檔時是否需要提及所有的鍵和值對? 我希望它不應該是..

此外,還有什麼能更新像圖像/ MP3等二進制文件提前

感謝您的支持代碼!

Vasudev

回答

0

我想你已經從這個移動了,但這裏的情況下,回答別人的更後。

這允許您更新特定的元數據來處理文件,同時保留所有其他值。

$m = new MongoClient(); 
$db = $m->mydb; 
$gridfs = $db->getGridFS(); 
$cursor = $gridfs->find(array('_id'=>new MongoID($_POST['_id']))); 
foreach ($cursor as $obj) { 
    $obj->file['Username'] = $_POST['name']; 
    $gridfs->save($obj->file); 
} 

因爲我們有_id在這裏,我們也可以使用$gridfs->findOne(array('_id' => new MongoID($_POST['_id'])));返回$obj直接代替cursor的。如果您這樣做,在嘗試更新文件之前,請務必測試$obj不是null(找不到文檔)。

$m = new MongoClient(); 
$db = $m->mydb; 
$gridfs = $db->getGridFS(); 
$obj = $gridfs->findOne(array('_id'=>new MongoID($_POST['_id']))); 
if ($obj) { 
    $obj->file['Username'] = $_POST['name']; 
    $gridfs->save($obj->file); 
}