MongoDB GridFS - MongoDB

What is the use of GridFS?

GridFS is the MongoDB specification which is used for storing and retrieving large files such as images, audio files, video files, etc. It is similar to a file system which stores files but its data will be stored within MongoDB collections. GridFS has the capability of storing files which are greater than its document size limit of 16MB.

GridFS will divide a file into chunks and will store each chunk of data in a separate document, each of maximum size 255k.

By default, GridFS uses two collections fs.files and fs.chunks for stroing file's metadata and chunks. Each chunk will be identified by its unique _id ObjectId field and the fs.files severs as a parent document. files_id field in the fs.chunks document links the chunk to its parent.

Below is a sample document of fs.files collection

The document will specify the file name, chunk size, uploaded date and length.

Below is a sample document of fs.chunks document

Adding Files to GridFS

Now, let’s store an mp3 file using GridFS put command. You can use mongofiles.exe utility present in the bin folder of the MongoDB installation folder.

Open the command prompt and navigate to the mongofiles.exe in the bin folder of MongoDB installation folder and type below code

In the above code, gridfs is the name of the database in which the file will be stored. If the database is not present, then MongoDB will automatically create a new document on the fly. Song.mp3 is the name of the uploaded file. To check if the file's document in database, you can use find query

Above command has returned below document

You can see that all the chunks present in fs.chunks collection related to the stored file with below code, using the document id returned in previous query

In this case, query has returned 40 documents which means that the whole mp3 document is divided in 40 chunks of data.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

MongoDB Topics