无法使用php更新Mongodb gridfs

无法使用php更新Mongodb gridfs,php,Php,我试图用文档ID更新Mongodb gridfs中的文档。最初我的文档是: { [_id] => MongoId Object ( [$id] => 5218a723db8af6920a3c6624 ) [Username] => 'Old Name' [Phone] => 'xxxxxxxxxx' [Address] => 'User address' [Email]

我试图用文档ID更新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
}
我只想更新“Username”字段的值。我使用以下代码对其进行了更新:

$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',
}
所以所有其他键和它们的值都消失了-我的代码出了什么问题? 更新文档时是否需要提及所有键和值对? 我希望不应该

此外,更新二进制文件(如image/mp3等)的代码是什么

提前感谢您的支持


瓦苏代夫

我想你已经离开了这一点,但这里有一个答案,以防其他人在追求它

这允许您更新与文件相关的特定元数据,同时保留所有其他值

$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);
}
因为我们这里有
\u id
,所以我们也可以使用
$gridfs->findOne(数组(''u id'=>新的MongoID($'u POST[''u id']))
直接返回
$obj
而不是
光标
。如果执行此操作,请确保在尝试更新文件之前测试
$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);
}