GridFS
GridFS is a specification provided by MongoDB for storing and retrieving large files such as images, audio files, video files, etc. It is a great solution for storing files larger than 16MB, which is the maximum document size in MongoDB.
Understanding GridFS
GridFS uses two collections to store files. One is the chunks collection that stores the binary data, and the other one is the files collection that stores the file’s metadata. Each chunk is identified by its unique ObjectId, and it contains a field called files_id
to relate it to the file document in the files collection.
When to Use GridFS?
You might want to use GridFS if:
- You need to store very large files (greater than 16MB)
- You need to access information from portions of large files without reading the entire files into memory
How to Use GridFS?
Here, we will look at how to use GridFS to store, retrieve, and delete files.
Storing Files with GridFS
To store a file to MongoDB using GridFS, you can use the mongofiles
utility. Here is an example:
mongofiles -d mydb put myBigFile.txt
In this command, -d mydb
specifies the database to use, put
is the command to store a new file, and myBigFile.txt
is the name of the file to store.
Retrieving Files from GridFS
To retrieve a file from MongoDB using GridFS, you can use the mongofiles
utility. Here is an example:
mongofiles -d mydb get myBigFile.txt
In this command, -d mydb
specifies the database to use, get
is the command to retrieve a file, and myBigFile.txt
is the name of the file to retrieve.
Deleting Files from GridFS
To delete a file from MongoDB using GridFS, you can use the mongofiles
utility. Here is an example:
mongofiles -d mydb delete myBigFile.txt
In this command, -d mydb
specifies the database to use, delete
is the command to delete a file, and myBigFile.txt
is the name of the file to delete.
Conclusion
GridFS is a powerful tool for handling large files in MongoDB. It breaks the file into chunks and stores each chunk as a separate document, allowing for efficient storage and retrieval of large files. With the mongofiles
utility, you can easily store, retrieve, and delete files using GridFS.