GridFS-A special feature of MongoDB
MongoDB provides a special specification named GridFS for storing and retrieving files such as images, audio files, video files, etc that exceed the BSON-document size limit of 16MB. It is kind of a file system to store files but its data is stored within MongoDB collections.
GridFS basically divides each file into several parts or chunks, instead of storing the file in a single document and each chunk is stored as a separate document. And the limits for the chunk size is 255k. GridFS uses two collection to store files: • Chunks collection(which stores the binary chunks) • Files collections(store the file’s metadata)
Chunks Collection: In the chunk collection, each document represent the distinct chunk of a file as represented in the GridFS. Following is the example to represent the chunk collection: { “_id” :<objectid>, “Files_id” :<objectid>, “number” :<num>, “data” :<binary> } Files Collection: Each document present in the files Collection represents a file in the GridFS. Following is the example of file collection. { "_id" : <ObjectId>, "length" : <num>, "chunkSize" : <num>, "upload_Date" : <timestamp>, "md5" : <hash>, "file_name" : <string>, "content_Type" : <string>, "aliases" : <string array>, "metadata" : <dataObject>, }
How to add files to the GridFS? Now to store the mp3 file using GridFS using the Put command. For this use the mongofiles.exe utility present in the bin folder of the MongoDB installation folder. Open the command prompt, navigate to the mongofiles.exe in the bin folder of the MongoDB installation folder and type the command: >mongofiles.exe -d GridFS put Song.mp3 Adding an mp3 file to GridFS:
In the chunk collection, each document represent the distinct chunk of a file as represented in the GridFS. Following is the example to represent the chunk collection
To show the mp3 file connect to the mongo server and navigate through the databases, use the gridfs database and execute the find() command inside the fs.files collection. >db.fs.files.find()
Advantages of GridFS:
• Helps to overcome file system limitation like storing large number of files. • For accessing selected portion of the files. • Storing user generated file content • Storing those documents whose size is greater than the 16MB. • Storing the files along with the databases and eradicating the problems like: Replicating the files to all needed servers How to delete the copies when the file is deleted? etc.
Conclusion: So GridFS is a very attractive feature of MongoDB which is useful not only for storing files that exceed 16MB but also for storing any files for which the need is to access without having to load the entire file into memory.










