Problem Statement
When should you use GridFS in MongoDB?
Explanation
GridFS is MongoDB's specification for storing and retrieving files that exceed the 16 MB BSON document size limit. It divides large files into chunks and stores each chunk as a separate document in two collections: fs.files for metadata and fs.chunks for actual data.
Use GridFS when you need to store files larger than 16 MB, when you need to access portions of files without loading the entire file into memory, or when your file system has limitations on the number of files per directory. For files smaller than 16 MB, storing them as binary data in regular documents is simpler and more efficient.
Code Solution
SolutionRead Only
// Upload file to GridFS
const bucket = new GridFSBucket(db)
const uploadStream = bucket.openUploadStream('video.mp4')
fs.createReadStream('./video.mp4').pipe(uploadStream)
// GridFS creates two collections:
// fs.files - file metadata
{
_id: ObjectId(),
filename: "video.mp4",
length: 52428800, // 50MB
chunkSize: 261120,
uploadDate: ISODate()
}
// fs.chunks - file data chunks
{
_id: ObjectId(),
files_id: ObjectId(),
n: 0, // Chunk number
data: BinData(...) // 255KB chunk
}