I tried to update a document in Mongodb gridfs with the document's ID. 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.
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'])));
to return the $obj
directly instead of a 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.
$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);
}