GridFS is the MongoDB specification for storing and retrieving huge documents which includes pictures, audio files, video documents, etc. It is kind of a file device to shop documents but its facts is saved inside MongoDB collections. GridFS has the functionality to store documents even extra than its report length restrict of 16MB.
GridFS divides a file into chunks and shops every chew of records in a separate record, each of maximum length 255k.
GridFS by way of default makes use of two collections fs.Documents and fs.Chunks to save the document's metadata and the chunks. Each chew is identified by using its particular _id ObjectId field. The fs.Files serves as a determine file. The files_id area within the fs.Chunks report links the chew to its figure.
Following is a pattern report of fs.Files collection −
{
"filename": "test.txt",
"chunkSize": NumberInt(261120),
"uploadDate": ISODate("2014-04-13T11:32:33.557Z"),
"md5": "7b762939321e146569b07f72c62cca4f",
"length": NumberInt(646)
}
The document specifies the document call, chew size, uploaded date, and period.
Following is a sample document of fs.Chunks file −
{
"files_id": ObjectId("534a75d19f54bfec8a2fe44b"),
"n": NumberInt(0),
"data": "Mongo Binary Data"
}
Adding Files to GridFS
Now, we will store an mp3 report the usage of GridFS the usage of the put command. For this, we can use the mongofiles.Exe utility present inside the bin folder of the MongoDB installation folder.
Open your command prompt, navigate to the mongofiles.Exe within the bin folder of MongoDB installation folder and kind the subsequent code −
>mongofiles.exe -d gridfs put song.mp3
Here, gridfs is the call of the database in which the record will be saved. If the database isn't always gift, MongoDB will mechanically create a new document on the fly. Song.Mp3 is the call of the record uploaded. To see the report's record in database, you could use find question −
>db.fs.files.find()
The above command lower back the subsequent record −
{
_id: ObjectId('534a811bf8b4aa4d33fdf94d'),
filename: "song.mp3",
chunkSize: 261120,
uploadDate: new Date(1397391643474), md5: "e4f53379c909f7bed2e9d631e15c1c41",
length: 10401959
}
We can also see all of the chunks found in fs.Chunks collection related to the saved document with the following code, the use of the record identity again within the preceding question −
>db.fs.chunks.find({files_id:ObjectId('534a811bf8b4aa4d33fdf94d')})
In my case, the question lower back 40 files which means that the complete mp3 report become divided in forty chunks of information.