Database Reference
In-Depth Information
Adding More Metadata to Stored Files
Sometimes you may want to add more metadata to your stored files. By default, the only other data that's added is
the
_id
field, which you might use to reference the data when you're storing a picture to a contact card. Unfortunately,
that might prove to be more of a restriction than a benefit when you want to start searching for your data through
these tags.
The following example shows how to store metadata for your uploaded data. This example builds on the previous
code block and the
$id
parameter in particular. Obviously, you can customize this yourself, using any other desired
search criteria:
// Specify the metadata to be added
$metadata = array('$set' => array("Tag" => "Avatar"));
// Specify the search criteria to which to apply the metadata
$criteria = array('_id' => $id);
// Insert the metadata
$db->grid->update($criteria, $metadata);
Retrieving Files
Of course, the ability to store your files in a database wouldn't do you any good if you weren't able to retrieve these
files later. Retrieving files is about as hard (read: easy!) as storing them. Let's look at two examples: the first retrieves
the filenames stored, while the second retrieves the files themselves.
The following example shows how to retrieve the filenames stored, which you accomplish using the
getFilename()
function:
// Connect to the database
$c = new MongoClient();
$db = $c->contacts;
// Initialize GridFS
$gridFS = $db->getGridFS();
// Find all files in the GridFS storage and store under the $cursor parameter
$cursor = $gridFS->find();
// Return all the names of the files
foreach ($cursor as $object) {
echo "Filename:".$object->getFilename();
}
That was easy! Of course, this example assumes that you have some data stored in your database. You might also
want to add more search parameters to the
find()
function after you've added a little more data or if you want to
search for more specific data. Note that the
find()
function searches through the metadata added to each uploaded
file (as detailed earlier in this chapter).
You might wonder how you go about retrieving the files themselves. After all, retrieving the data is probably what
you'll be using the most in the end. You accomplish this by using the
getBytes()
function to send it to your browser.
The next example uses the
getBytes()
function to retrieve a previously stored image. Note that you can retrieve the
_id
parameter by querying the database (the following example just makes up some parameters). Also, it's mandatory
to specify the content type because, logically, this is not recognized by the browser when you build up the data again:
// Connect to the database
$c = new MongoClient();
// Specify the database name
$db = $c->contacts;