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:

[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;
        //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.