When to Use GridFS in MongoDB: Key Uses and Examples
GridFS in MongoDB when you need to store and retrieve files larger than 16MB, which is the document size limit. GridFS splits large files into smaller chunks and stores them across multiple documents, making it ideal for handling big files like videos, images, or backups.How It Works
GridFS works like a smart file cabinet inside MongoDB. Instead of saving a big file as one piece, it cuts the file into small chunks (default 255KB each) and stores each chunk as a separate document. This way, MongoDB can handle files bigger than its usual 16MB limit.
Think of it like slicing a large cake into small pieces so you can store and serve it easily. When you want the whole cake back, GridFS puts all the pieces together in the right order.
This system also stores file metadata (like filename, upload date, and size) separately, making it easy to find and manage files.
Example
This example shows how to upload and download a file using GridFS with the MongoDB Node.js driver.
const { MongoClient, GridFSBucket } = require('mongodb'); const fs = require('fs'); async function run() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const db = client.db('myfilesdb'); const bucket = new GridFSBucket(db); // Upload a file const uploadStream = bucket.openUploadStream('example.txt'); fs.createReadStream('example.txt').pipe(uploadStream) .on('error', (error) => console.error('Upload error:', error)) .on('finish', () => { console.log('File uploaded successfully'); // Download the file const downloadStream = bucket.openDownloadStreamByName('example.txt'); downloadStream.pipe(fs.createWriteStream('downloaded_example.txt')) .on('error', (error) => console.error('Download error:', error)) .on('finish', () => { console.log('File downloaded successfully'); client.close(); }); }); } run().catch(console.error);
When to Use
Use GridFS when you need to store files larger than 16MB, which is MongoDB's document size limit. It is perfect for:
- Storing large media files like videos, audio, and images.
- Saving backups or archives that exceed normal document sizes.
- Handling files that need to be streamed or partially retrieved.
If your files are small and fit within 16MB, storing them directly in a document as binary data is simpler and faster. But for anything bigger, GridFS is the right choice.
Key Points
- GridFS splits large files into chunks to bypass MongoDB's 16MB limit.
- It stores file metadata separately for easy management.
- Ideal for large files like videos, images, and backups.
- Supports streaming upload and download of files.
- Use normal binary storage for files smaller than 16MB for simplicity.