GridFS and Capped Collections


GridFS and Capped Collections Interview with follow-up questions

1. What is GridFS in MongoDB and when should it be used?

GridFS is a specification (implemented in the drivers and mongofiles) for storing files larger than the 16MB BSON document limit inside MongoDB. It splits a file into 255KB chunks, storing each chunk as a document in a fs.chunks collection, with one metadata document per file (filename, length, upload date, content type, custom fields) in fs.files.

// Streaming a file in via the Node driver
const bucket = new GridFSBucket(db)
fs.createReadStream("video.mp4").pipe(bucket.openUploadStream("video.mp4"))

When to use it:

  • The file exceeds 16MB, or
  • You need to stream or range-read parts of a file (serve a byte range without loading the whole thing), or
  • You want files to live inside the database for unified backup, replication, and access control alongside your data.

The gotcha interviewers want: for most modern applications, object storage (S3, GCS, Azure Blob) is the better default — it's cheaper, scales independently, integrates with CDNs, and doesn't bloat your database or compete for the WiredTiger cache. A common, strong pattern is storing the file in object storage and keeping just the URL/metadata in MongoDB. Reach for GridFS specifically when you need files co-located with data for consistency, backup, or self-contained deployment reasons.

↑ Back to top

Follow-up 1

How does GridFS store files?

GridFS stores files by dividing them into smaller chunks, typically 255KB in size. Each chunk is stored as a separate document in the chunks collection. The chunks collection contains the following fields:

  • files_id: The _id of the file in the files collection.
  • n: The sequence number of the chunk.
  • data: The binary data of the chunk.

The files collection contains the metadata of the file, such as filename, content type, and other custom attributes. The files collection has a reference to the chunks collection through the _id field.

Follow-up 2

What are the advantages of using GridFS?

There are several advantages of using GridFS:

  1. Scalability: GridFS allows you to store and retrieve large files that exceed the BSON document size limit of 16MB. It automatically divides the file into smaller chunks and distributes them across multiple documents, enabling efficient storage and retrieval of large files.

  2. Integration with MongoDB: GridFS is integrated with MongoDB, which means you can use the same tools and APIs to work with both your regular data and large files. This simplifies the development and maintenance of your application.

  3. Metadata support: GridFS allows you to store metadata along with the file, such as filename, content type, and other custom attributes. This makes it easy to organize and search for files based on their metadata.

  4. Streaming support: GridFS supports streaming, which means you can read and write large files in small chunks, reducing memory usage and improving performance.

Follow-up 3

Can you explain how GridFS handles large files?

GridFS handles large files by dividing them into smaller chunks, typically 255KB in size. Each chunk is stored as a separate document in the chunks collection. When you store a file using GridFS, it automatically divides the file into chunks and distributes them across multiple documents. When you retrieve the file, GridFS reassembles the chunks into the original file.

GridFS uses a unique identifier, called files_id, to associate the chunks with the file. The files_id is stored in both the files collection and the chunks collection. This allows GridFS to retrieve the chunks that belong to a specific file and reassemble them into the original file.

GridFS also stores the metadata of the file, such as filename, content type, and other custom attributes, in the files collection. This makes it easy to retrieve the metadata along with the file.

Follow-up 4

What are the limitations of GridFS?

GridFS has a few limitations:

  1. Increased complexity: Using GridFS adds complexity to your application compared to storing files directly in the database as BSON documents. You need to handle the division and reassembly of files into chunks, manage the metadata separately, and handle the retrieval and storage of files using the GridFS API.

  2. Performance impact: Storing and retrieving files using GridFS can have a performance impact compared to storing files directly in the database as BSON documents. This is because GridFS involves additional operations, such as dividing and reassembling files, and managing the metadata separately.

  3. Limited query capabilities: GridFS does not provide the same query capabilities as regular MongoDB queries. You can only query files based on their metadata, such as filename or content type, but not based on the content of the file itself.

  4. Additional storage overhead: GridFS adds additional storage overhead compared to storing files directly in the database as BSON documents. This is because each chunk is stored as a separate document in the chunks collection, which requires additional space.

2. What are Capped Collections in MongoDB?

A capped collection is a fixed-size collection that behaves like a circular buffer: documents are stored in insertion order, and once the collection hits its size cap, MongoDB automatically overwrites the oldest documents to make room for new ones — no manual deletion needed.

db.createCollection("logs", { capped: true, size: 1048576, max: 10000 })
  • size (bytes, required) — the hard cap; max (optional) — an additional document-count cap.
  • Documents are returned in insertion order naturally (no sort/index needed) and you can tail them with a tailable cursor.

Characteristics and constraints interviewers probe:

  • High-throughput inserts — preallocated, in-order storage makes writes very fast.
  • No arbitrary deletes — you cannot deleteOne; the only removal is automatic aging-out.
  • Updates can't grow a document beyond its original size (would break in-order layout).
  • Can't be sharded.

Use cases: rolling logs, audit trails, event/metric buffers, caches of recent items — anywhere you want the last N entries and don't care about old ones. The classic real-world example is MongoDB's own oplog, which is a capped collection.

Modern note: for time-based expiry rather than size-based, a TTL index on a regular collection is often the better fit, and time series collections (5.0+) are purpose-built for metrics/events.

↑ Back to top

Follow-up 1

How do you create a capped collection?

To create a capped collection in MongoDB, you can use the createCollection command with the capped option set to true. Here's an example:

use myDatabase
db.createCollection('myCappedCollection', { capped: true, size: 100000, max: 100 })

This will create a capped collection named myCappedCollection with a maximum size of 100,000 bytes and a maximum of 100 documents.

Follow-up 2

What are the characteristics of a capped collection?

The characteristics of a capped collection in MongoDB are:

  • It has a fixed size and a fixed number of documents
  • Once the maximum size or number of documents is reached, new documents will replace the oldest documents
  • Documents are stored in the order of their insertion
  • Capped collections are ideal for storing logs or other data that needs to be stored in a circular buffer fashion

Follow-up 3

In what scenarios would you use a capped collection?

Capped collections in MongoDB are useful in scenarios where you need:

  • A fixed-size collection that automatically overwrites the oldest data
  • A high-performance storage for logs or other time-series data
  • A circular buffer-like behavior for storing data

Some examples of use cases for capped collections include:

  • Storing application logs
  • Storing sensor data
  • Storing real-time metrics

Follow-up 4

What are the limitations of capped collections?

There are some limitations to consider when using capped collections in MongoDB:

  • Capped collections cannot be sharded
  • You cannot update documents in a capped collection, you can only insert or delete documents
  • Indexes on capped collections have some limitations, such as not supporting unique indexes or sparse indexes
  • Once a capped collection is created, its size and maximum number of documents cannot be changed

It's important to carefully consider these limitations before using capped collections in your MongoDB database.

3. How does MongoDB handle large files?

A single MongoDB document is capped at 16MB, so anything larger can't be stored as one document. MongoDB's built-in answer is GridFS, which splits a large file across two collections:

  • fs.chunks — the file broken into 255KB chunks, each chunk a separate document (the last chunk may be smaller).
  • fs.files — one metadata document per file: filename, total length, chunk size, upload date, content type, and any custom fields.

An index on { files_id: 1, n: 1 } lets MongoDB fetch chunks in order, and because the file is chunked you can stream it or read a byte range without loading the whole thing into memory.

const bucket = new GridFSBucket(db)
bucket.openDownloadStreamByName("video.mp4").pipe(res)   // stream out

What interviewers want you to add — the gotcha: GridFS isn't the only or even the usual answer in 2026. For most applications, object storage (Amazon S3, GCS, Azure Blob) is preferred for large/binary files: cheaper, scales independently of the database, CDN-friendly, and it keeps big blobs out of the WiredTiger cache. The common pattern is to store the file in object storage and keep only its URL and metadata in MongoDB. Choose GridFS specifically when you need files co-located with your data for unified backup, replication, transactions, or access control.

↑ Back to top

Follow-up 1

What role does GridFS play in handling large files?

GridFS is a file storage mechanism in MongoDB that allows you to store and retrieve large files that exceed the BSON document size limit of 16 MB. It breaks up large files into smaller chunks and stores them as separate documents in a collection. GridFS also provides a way to associate metadata with the file, such as its filename, content type, and size. This makes it easier to manage and query large files in MongoDB.

Follow-up 2

What is the maximum file size that MongoDB can handle?

The maximum file size that MongoDB can handle depends on the version of MongoDB you are using. In MongoDB 4.4 and earlier, the maximum file size is 16 MB, which is the BSON document size limit. However, starting from MongoDB 4.6, the maximum file size has been increased to 48 MB. If you need to store larger files, you can use GridFS, which allows you to store files of any size by breaking them up into smaller chunks.

Follow-up 3

How does MongoDB split large files for storage?

MongoDB splits large files for storage using a feature called GridFS. GridFS breaks up a large file into smaller chunks, typically 255 KB in size, except for the last chunk which can be smaller. Each chunk is stored as a separate document in a collection. GridFS also stores metadata about the file, such as its filename, content type, and size. This allows MongoDB to efficiently store and retrieve large files by dividing them into manageable chunks.

4. Can you explain the difference between regular collections and capped collections in MongoDB?

Aspect Regular collection Capped collection
Size Grows dynamically, no fixed limit Fixed maximum size (and optional max count)
Order No guaranteed order without a sort/index Preserves insertion order natively
Eviction Documents persist until you delete them Oldest documents auto-overwritten when full (circular buffer)
Deletes deleteOne/deleteMany allowed No arbitrary deletes — only automatic aging-out
Updates Unrestricted Allowed, but can't grow a document past its original size
Sharding Supported Not shardable
db.createCollection("audit", { capped: true, size: 1048576, max: 5000 })

When to use which — what interviewers want:

  • Regular: the default for virtually all data — you need full CRUD, growth, indexing flexibility, and sharding.
  • Capped: rolling logs, audit trails, event/metric buffers, "last N items" caches — fast in-order inserts with automatic cleanup. MongoDB's own oplog is a capped collection.

The gotcha: if you need time-based expiry rather than size-based, reach for a TTL index on a regular collection instead; and for metrics/events at scale, time series collections (5.0+) usually beat hand-rolling a capped collection.

↑ Back to top

Follow-up 1

Can you modify the size of a capped collection after it has been created?

No, you cannot modify the size of a capped collection after it has been created. The size of a capped collection is defined when it is created and cannot be changed. If you need to change the size, you will need to create a new capped collection with the desired size and migrate the data from the old collection to the new one.

Follow-up 2

Can you delete documents from a capped collection?

Yes, you can delete documents from a capped collection. However, it's important to note that deleting documents from a capped collection does not free up disk space. Instead, the space occupied by the deleted documents is reused for new documents. If you need to reclaim disk space, you will need to drop the entire capped collection and recreate it.

Follow-up 3

What are the performance implications of using capped collections?

Capped collections offer some performance benefits compared to regular collections. Since capped collections store documents in the insertion order, queries that retrieve documents in the order of insertion can be faster. Additionally, capped collections use a fixed amount of disk space, which can improve write performance as there is no need to allocate additional space for new documents. However, it's important to note that capped collections have some limitations, such as the inability to update documents or delete documents selectively.

5. How does MongoDB ensure efficient retrieval of large files stored using GridFS?

GridFS makes large-file retrieval efficient through chunking plus indexing, which lets MongoDB read files in order and even fetch just part of a file.

The mechanics:

  • A file is split into 255KB chunks in fs.chunks, each tagged with a files_id (linking it to its fs.files metadata document) and a sequential chunk number n.
  • GridFS creates a unique compound index on { files_id: 1, n: 1 }, so MongoDB can locate and pull a file's chunks in exact order with an efficient index scan rather than a collection scan.
  • Because the file is chunked, the driver can stream it to the client and serve byte-range requests — reading only the chunks that cover the requested range (e.g. seeking within a video) instead of loading the whole file into memory.
const bucket = new GridFSBucket(db)
// Range read: skip into the file and stream just the needed chunks
bucket.openDownloadStreamByName("video.mp4", { start: 1_000_000, end: 2_000_000 }).pipe(res)

What interviewers want you to add: the { files_id, n } index is what keeps retrieval fast; streaming keeps memory bounded regardless of file size. But also note the trade-off — for high-traffic file serving, object storage + CDN typically outperforms GridFS, so GridFS is the right call mainly when you need files inside MongoDB for backup, replication, or access-control consistency.

↑ Back to top

Follow-up 1

What indexing strategies are used by GridFS?

GridFS uses two indexes to optimize the retrieval of files and chunks:

  1. Index on the files collection: GridFS creates an index on the filename field of the files collection. This allows for efficient retrieval of files based on their filename.

  2. Index on the chunks collection: GridFS creates a compound index on the files_id and n (chunk number) fields of the chunks collection. This index enables efficient retrieval and sorting of chunks for a given file.

Follow-up 2

How does GridFS handle concurrent read and write operations?

GridFS handles concurrent read and write operations by leveraging MongoDB's concurrency control mechanisms. MongoDB uses a multi-version concurrency control (MVCC) system to ensure consistency and isolation of concurrent operations. When multiple clients attempt to read or write to the same file, MongoDB's locking and transaction management mechanisms ensure that the operations are executed in a safe and consistent manner. This allows GridFS to handle concurrent read and write operations efficiently without compromising data integrity.

Follow-up 3

Can you explain the role of the files and chunks collections in GridFS?

In GridFS, the files collection stores metadata about the files being stored, such as the filename, content type, and other optional attributes. Each file in the files collection is associated with one or more chunks stored in the chunks collection. The chunks collection stores the actual data of the file, divided into smaller chunks. Each chunk is a separate document in the chunks collection and is linked to the corresponding file document in the files collection using a unique file_id. This separation allows for efficient storage and retrieval of large files in MongoDB, as well as the ability to handle files that exceed the BSON document size limit.

Live mock interview

Mock interview: GridFS and Capped Collections

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.

Next lesson Aggregation Framework and MapReduce →