MongoDB GridFS

GridFS is used to store and restore files (such as pictures, audio, video, etc.) that exceed 16M (BSON file limit).

GridFS is also a way of storing files, but it is stored in a collection of MonoDB.

GridFS can better store files larger than 16M.

GridFS will split a large file object into multiple small chunks (file fragments), generally 256k /piece. Each chunk will be stored as a document in MongoDB in the chunks collection.

GridFS uses two collections to store a file: fs.files and fs.chunks.

The actual content of each file is stored in chunks (binary data), and meta data (filename, content_type, and user-defined attributes) related to the file will be stored in the files collection.

Here is a simple fs.files collection document:

   "filename": "test.txt",
   "chunkSize": NumberInt(261120),
   "uploadDate": ISODate("2014-04-13T11:32:33.557Z"),
   "md5": "7b762939321e146569b07f72c62cca4f",
   "length": NumberInt(646)

Here is a simple fs.chunks collection document:

   "files_id": ObjectId("534a75d19f54bfec8a2fe44b"),
   "n": NumberInt(0),
   "data": "Mongo Binary Data"

GridFS add files

Now we use GridFS's put command to store mp3 files. Invoke the mongofiles.exe tool in the MongoDB installation directory.

Open a command prompt, go to the bin directory of the MongoDB installation directory, find mongofiles.exe, and enter the following code:

>mongofiles.exe -d gridfs put song.mp3

-d gridfs Specifies the name of the database where the file is stored. If the database does not exist, MongoDB will automatically create it. If the database does not exist, MongoDB will automatically create it. Song.mp3 is the audio file name.

Use the following command to view the documentation of the files in the database:


The following document data is returned after the above command is executed:

   _id: ObjectId('534a811bf8b4aa4d33fdf94d'), 
   filename: "song.mp3", 
   chunkSize: 261120, 
   uploadDate: new Date(1397391643474), md5: "e4f53379c909f7bed2e9d631e15c1c41",
   length: 10401959 

We can see all the blocks in the fs.chunks collection. Below we get the _id value of the file. We can get the chunk data based on this _id:


In the above example, the query returned data for 40 documents, which means that the mp3 file was stored in 40 blocks.

Welookups is optimized for learning.© 2018 -

All Right Reserved and you agree to have read and accepted our term and condition.