Database Reference
In-Depth Information
// Initialize the GridFS files collection
$gridFS = $db->getGridFS();
// Specify the search parameter for the file
$id = new MongoId('4c555c70be90968001080000');
// Retrieve the file
$file = $gridFS->findOne(array('_id' => $id));
// Specify the header for the file and write the data to it
header('Content-Type: image/jpeg');
echo $file->getBytes();
exit;
Deleting Data
You can ensure that any previously stored data is removed by using the delete() function. This function takes one
parameter: the _id of the file itself. The following example illustrates how to use the delete() function to delete the
file matching the Object ID 4c555c70be90968001080000:
// Connect to the database
$c = new MongoClient();
// Specify the database name
$db = $c->contacts;
// Initialize GridFS
$gridFS = $db->getGridFS();
// Specify the file via it's ID
$id = new MongoId('4c555c70be90968001080000');
$file = $gridFS->findOne(array('_id' => $id));
// Remove the file using the remove() function
$gridFS->delete($id);
Summary
In this chapter, you've taken an in-depth look at how to work with MongoDB's PHP driver. For example, you've seen
how to use the most commonly used functions with the PHP driver, including the insert() , update() , and modify()
functions. You've also learned how to search your documents by using the PHP driver's equivalent of the find()
function. Finally, you've learned how to leverage DBRef 's functionality, as well as how to store and retrieve files
with GridFS.
One chapter couldn't possibly cover everything there is to know about using the PHP driver for MongoDB;
nonetheless, this chapter should provide the necessary basics to perform most of the actions you'd want to
accomplish with this driver. Along the way, you've also learned enough to use the server-side commands whenever
the going gets a little more complicated.
In the next chapter, you'll explore the same concepts, but for the Python driver instead.
 
Search WWH ::




Custom Search