1

我尝试使用文档的 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
}

我只想更新“用户名”字段的值。我使用以下代码对其进行更新:

$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 等)的代码是什么?

提前感谢您的支持!

瓦苏杰夫

4

1 回答 1

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);
}

由于我们有_idhere,我们也可以使用直接$gridfs->findOne(array('_id' => new MongoID($_POST['_id'])));返回$obj而不是 a 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);
}
于 2014-02-21T07:09:33.577 回答