$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[July 22, 2026] MongoDB

MongoDB GridFS: File Management

MongoDB GridFS: File Management

────────────────────────────────────────────────────────

MongoDB GridFS: File Management

Tip: GridFS Bucket

$bucket = DB::connection('mongodb')->getMongoDB()->selectGridFSBucket();

Gotcha: Two Collections

GridFS uses fs.files (metadata) and fs.chunks (file data). Don't query them directly.

Tip: Upload with Metadata

$stream = fopen('/path/to/file.pdf', 'r');
$fileId = $bucket->uploadFromStream('file.pdf', $stream, [
    'metadata' => ['author' => 'John', 'type' => 'pdf'],
]);

Gotcha: GridFS Doesn't Support Partial Reads Well

Reading a small portion of a large file still loads all chunks.

Tip: Query by Metadata

$files = $bucket->find(['metadata.type' => 'pdf']);

Gotcha: GridFS vs S3

For production file storage, prefer S3. GridFS is good for small deployments or transactional needs.

Tip: Embed or Reference? The 80/20 Rule

If you always access data together, embed it. If you access it independently, reference it. The 16MB document size limit is the hard boundary — stay under 1MB for most documents.

Tip: Index Your Query Patterns, Not All Fields

Creating indexes on every field wastes RAM. Use explain() to find in-memory sorts and collection scans. Index only what your actual queries filter on.

Gotcha: No Transaction Rollback for Index Builds

Building an index on a large collection can take hours. If it fails midway, the partial index is silently discarded. Plan index builds during maintenance windows.

Senior Insight

The MongoDB replica set is the foundation of high availability. I configure at least three data-bearing members and one arbiter (for odd-numbered voting). The election process takes 5-10 seconds by default — not instantaneous. Applications need to handle the 'not primary' error gracefully with retry logic. The MongoDB driver retries reads and writes automatically, but the application must have timeout and retry strategies that align with the replica set's election timeout.

Source: MongoDB Developer Center (https://www.mongodb.com/developer/), MongoDB Engineering Blog (https://www.mongodb.com/blog/channel/engineering-blog), Studio 3T Blog (https://studio3t.com/blog/)

────────────────────────────────────────────────────────
<-- back to posts