[英]Not able to update Mongodb gridfs with php
I tried to update a document in Mongodb gridfs with the document's ID. 我试图用文档的ID更新Mongodb gridfs中的文档。 Initially my document was : 最初,我的文档是:
{
[_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
}
And I wanted to update the value of only the 'Username' field. 我只想更新“用户名”字段的值。 I used the following code to update it : 我使用以下代码对其进行了更新:
$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.
}
But after update What it made to my document is this : 但是更新后对我的文档的影响是:
{
[_id] => MongoId Object (
[$id] => 5218a723db8af6920a3c6624
),
[Username] => 'New Name',
}
So all other keys and their values disappeared - What went wrong in my code? 因此所有其他键及其值都消失了-我的代码出了什么问题? Do I need to mention all keys and values pairs while updating a document? 更新文档时是否需要提及所有键和值对? I hope it should not be.. 我希望不会。
Further, what can be the code to update the binary file like image / mp3 etc. 此外,更新二进制文件(例如image / mp3等)的代码是什么?
Thanks in advance for your support! 预先感谢您的支持!
Vasudev 瓦苏杰夫
I assume you've moved on from this, but here's the answer in case anyone else is after it. 我认为您已经摆脱了这一点,但是如果其他人追随它,这就是答案。
This allows you to update specific metadata to do with a file, while leaving all the other values alone. 这样,您就可以更新特定的元数据来处理文件,而无需考虑其他所有值。
$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);
}
Since we have the _id
here, we could also use $gridfs->findOne(array('_id' => new MongoID($_POST['_id'])));
因为这里有_id
,所以我们也可以使用$gridfs->findOne(array('_id' => new MongoID($_POST['_id'])));
to return the $obj
directly instead of a cursor
. 直接返回$obj
而不是cursor
。 If you do this, just be sure to test that $obj
isn't null
(no document found) before you try to update the file. 如果这样做,请确保在尝试更新文件之前,先测试$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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.