You’ve quickly put together the code to add files to MongoDB. But as any good DBA and Developer knows not everything that goes into your database should stay there.

Yes, you already figured out it’s as simple as $grid->remove(). Here is something to keep in mind. MongoGridFS::remove won’t present you with a message if it failed.┬áTo ensure that a file was successfully removed use MongoDB::lastError(). You’ll get an array in return that will show something along the lines of:

Array
(
[err] =>
[n] => 0
[ok] => 1
)

The field to watch is “ok”. The value of “1″ will return if the remove went according to plan. Otherwise you’ll get “0″ and it’s time to check the value for “err”. If you’re wondering about the “n” its the number of files that were removed.

In practice your code could look something like this:

/*
* function remove
* Removes files from Mongo and captures error if failed
* @return mixed
*/
public function remove($criteria)
{
    //Get the GridFS Object
    $grid = $db->getGridFS();

    //Setup some criteria to search for file
    $id = new MongoID($criteria['_id']);

    //Remove file
    $grid->remove(array('_id'=>$id), true);

    //Get lastError array
    $errorArray = $db->lastError();
    if ($errorArray['ok'] == 1 ) {
        $retval = true;
    }else{
        //Send back the error message
        $retval = $errorArray['err'];
    }

    return $retval;
}

With a few short lines you’re able to capture the error message and do whatever you like with it. Hopefully this helps keep your fs.files and fs.chunks collections clean.

Leave a reply

required

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>