QA
Beginner LevelMongoDB & Mongoose

What is GridFS and how does it store files exceeding the 16MB BSON limit?

❓ Interview Prompt: Explain GridFS specification, 16MB BSON document size limit, chunking files into 255KB blocks (fs.chunks), and metadata (fs.files).

MongoDB BSON documents are capped at 16MB maximum size. GridFS is a specification for storing and retrieving files exceeding 16MB:

How GridFS Works:

Splits large files into 255KB chunks stored across two internal system collections:

1
fs.files: Holds file metadata (filename, length, uploadDate, md5).
2
fs.chunks: Holds raw binary data chunks referenced by 'files_id'.

Code Implementation Example

typescript
import mongoose from 'mongoose';
import fs from 'fs';

async function uploadLargeFile(filePath: string, filename: string) {
  const db = mongoose.connection.db;
  const bucket = new mongoose.mongo.GridFSBucket(db!, { bucketName: 'uploads' });

  // Stream large file to GridFS bucket
  fs.createReadStream(filePath)
    .pipe(bucket.openUploadStream(filename))
    .on('finish', () => console.log('Upload complete!'));
}
💡Streaming large video/pdf files to GridFS bucket storage.
🎯 Interview Key Takeaway

Use GridFS to store files exceeding the 16MB BSON document limit by chunking them into fs.files and fs.chunks collections.

#GridFS#Binary Storage#Large Files#Beginner
Back to all MongoDB & Mongoose Questions→

More MongoDB & Mongoose Interview Questions

Beginner LevelMongoDB & Mongoose

How does the MongoDB Aggregation Pipeline work? Explain $match, $group, $lookup, and $project.

Beginner LevelMongoDB & Mongoose

What is MongoDB and how does the BSON document data model work?

Beginner LevelMongoDB & Mongoose

What is the structure of a MongoDB ObjectId and how is it generated?