Latest web development tutorials

MongoDB GridFS

GridFS for storing and restoring those over 16M (BSON file limit) files (such as: images, audio, video, etc.).

One way is GridFS file storage, but it is in the collection is stored in MonoDB.

GridFS better memory than 16M documents.

GridFS will target large files into multiple smaller chunk (file fragment), typically 256k /, one for each chunk as a document of MongoDB (document) is stored in the chunks collection.

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

The actual contents of each file is stored in chunks (binary data), the meta data and documents relating to the (filename, content_type, as well as user-defined attributes) it will be stored in files in the collection.

The following is a collection of simple fs.files documents:

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

The following is a collection of simple fs.chunks documents:

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

GridFS Add File

Now we use the put command GridFS to store mp3 files. Call MongoDB installation directory bin of mongofiles.exe tool.

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

>mongofiles.exe -d gridfs put song.mp3

GridFS is the name of the data file is stored. If the database does not exist, MongoDB will be automatically created. Song.mp3 is an audio file name.

Use the following commands to view documents in the database file:

>db.fs.files.find()

After executing the above command returns the following document data:

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

We can see all the blocks fs.chunks set, we get the following _id value document, we can get the block (chunk) of data in accordance with this _id:

>db.fs.chunks.find({files_id:ObjectId('534a811bf8b4aa4d33fdf94d')})

The above example, the query returns the data 40 of the document, which means that mp3 files are stored in 40 blocks.