MongoDB and GridFS
OverviewObjective
Learn how to store and retrieve files from the database using Mongo’s GridFS and ProdigyView.
Requirements
Installed PECL Mongo Extension
A Mongo Database
Understanding of MongoDB Basics with ProdigyView
Understanding of connecting to a database in ProdigyView
Estimated Time
10 Minutes
Follow Along With Code Example
1. Download a copy of the example code at www.prodigyview.com/source.
2.Install the system in an environment you feel comfortable testing in.
3.Proceed to examples/database/MongoGridFS.php
www.prodigyview.com
What Is GridFSThe GridFS is MongoDB’s way of storing files in the database. The files are stored in binary chunks that are around 256k in size.
File
GridFS
Chunk
Chunk
Chunk
Chunk
Chunk
Chunk
File InformationBefore the file is entered into Mongo, we need to setup options and variables. The data inserted with the file will become the meta data. The data is used to describe the file stored.
1. Insert data will act as the file meta data
2.Set the option to GridFS to true
3. Set the file to the location of on the server
Insert FileThen pass the insert data(meta data) and the options to PVDatabase::insertStatement() and the process of putting the file in the database will be handled for you.
1. The collection name 2. The meta data about the file
3. The options for uploading4. Returns a Mongo ID
Searching GridFSSearching in GridFS uses the same syntax as a regular search in ProdigyView except the gridFS option has to be set to true.
1. Search based on these arguments 2. Set the collection name
3. Set gridFS to true
Getting a Single FileAlso similar is retrieving a single file. The only difference again is to the gridFS option and combine it with the findOne option.
1. Set gridFS to true
2. Set findOne to True
Displaying The ImageIn our example, we uploaded images to the database. Now we need to retrieve the image and display it. Using getBytes() method, we can read in the chunks from the document retrieved from gridFS. This will return a string of bytes.
1. Get the image bytes from the result 2. Write the bytes to file
3. Display the image
www.prodigyview.com
Updating GridFSWhen updating a file in gridFS, we can modify the meta data of the file. The update mechanics work the same way when updating a normal document except the gridFS must be set to true. The file itself will be unaltered.
1. Collection name 2. The fields to update 3. Where to update
4. Set gridFS to true
Deleting File
The final action is deleting a file. On delete, the meta data and chunks be removed from the database. The same syntax from the select statement is used.
www.prodigyview.com
API ReferenceFor a better understanding of the database, visit the api by clicking on the link below.
PVDatabase
www.prodigyview.com
More Tutorials
For more tutorials, please visit:
http://www.prodigyview.com/tutorials