MongoDB, as a NoSQL database, is optimized for storing documents. But when you need to store large files (images, videos, PDFs and so on), the 16 MB document size limit can get in the way. This is where GridFS comes in. MongoDB's GridFS feature lets you store large files by splitting them into pieces and manage them easily. In this post we'll cover what GridFS is, how it works, its advantages and how to use it with Go.
What Is GridFS?
GridFS is a specification MongoDB provides for storing large files. Even if a file is larger than 16 MB, it splits it into smaller pieces (chunks), stores them and links them to metadata. GridFS uses two collections:
fs.files: Stores file metadata (name, size, upload date, etc.).fs.chunks: Stores the binary pieces of the files. Each chunk is 255 KB by default.
Key Features:
- Large File Support: Stores files that exceed the 16 MB limit by splitting them into chunks.
- Flexibility: Can store images, videos, audio files or any binary data.
- Integration: Works easily with MongoDB clients and drivers.
- Scalability: Compatible with MongoDB's replication and sharding features.
Why Use GridFS?
Storing small documents in MongoDB is easy, but relying on the file system for large files adds extra complexity (backups, scaling, metadata management). GridFS solves these problems and keeps file storage inside the database.
Advantages:
- Unified Management: Files and metadata live in the same database, and replication and backups come for free.
- Sharding: Large file collections can be distributed with sharding.
- Easy Access: Uploading, downloading and searching files is simple with the MongoDB drivers.
- Flexible Metadata: You can attach custom metadata to files (e.g. category, description).
Using GridFS with Go
To upload and download files to GridFS with Golang, we use the MongoDB Go driver and its GridFS package.
Installation
go get go.mongodb.org/mongo-driver/mongo
go get go.mongodb.org/mongo-driver/mongo/gridfsExample: Uploading and Downloading a File
package main
import (
"context"
"fmt"
"io"
"os"
"time"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/gridfs"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
mongoURI = "mongodb://localhost:27017"
dbName = "mydatabase"
)
func connectGridFS() (*mongo.Client, *mongo.Database, *gridfs.Bucket, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoURI))
if err != nil {
return nil, nil, nil, err
}
db := client.Database(dbName)
bucket, err := gridfs.NewBucket(db)
if err != nil {
return nil, nil, nil, err
}
return client, db, bucket, nil
}
func uploadFile(filePath, filename string, metadata interface{}) (primitive.ObjectID, error) {
client, _, bucket, err := connectGridFS()
if err != nil {
return primitive.NilObjectID, err
}
defer client.Disconnect(context.Background())
file, err := os.Open(filePath)
if err != nil {
return primitive.NilObjectID, err
}
defer file.Close()
uploadOpts := options.GridFSUpload().SetMetadata(metadata)
uploadStream, err := bucket.OpenUploadStream(filename, uploadOpts)
if err != nil {
return primitive.NilObjectID, err
}
defer uploadStream.Close()
if _, err := io.Copy(uploadStream, file); err != nil {
return primitive.NilObjectID, err
}
fmt.Println("✅ File uploaded, ID:", uploadStream.FileID)
return uploadStream.FileID.(primitive.ObjectID), nil
}
func downloadFile(fileID primitive.ObjectID, outputPath string) error {
client, _, bucket, err := connectGridFS()
if err != nil {
return err
}
defer client.Disconnect(context.Background())
downloadStream, err := bucket.OpenDownloadStream(fileID)
if err != nil {
return err
}
defer downloadStream.Close()
outputFile, err := os.Create(outputPath)
if err != nil {
return err
}
defer outputFile.Close()
if _, err := io.Copy(outputFile, downloadStream); err != nil {
return err
}
fmt.Println("📥 File downloaded:", outputPath)
return nil
}
func main() {
metadata := map[string]interface{}{
"category": "documents",
"uploaded_by": "user1",
"upload_date": time.Now(),
}
fileID, err := uploadFile("sample.pdf", "sample.pdf", metadata)
if err != nil {
fmt.Println("🚨 Upload error:", err)
return
}
if err := downloadFile(fileID, "downloaded_sample.pdf"); err != nil {
fmt.Println("🚨 Download error:", err)
}
}GridFS Workflow (Mermaid Diagram)
graph TD
A[User] --> B[File Upload]
B --> C[GridFS: Upload]
C --> D[fs.files: Metadata]
C --> E[fs.chunks: Chunks]
F[File Download] --> G[GridFS: Download]
G --> E
G --> D
G --> H[File Reassembly]
H --> I[File to User]
I --> AWhere Is GridFS Used?
- Media Storage: Large image, video or audio files.
- Document Management: Storing files like PDFs and Word documents together with their metadata.
- Web Applications: Managing user-uploaded content.
- Database Backups: Since files live in the database, backing them up is easy.
Note: GridFS is a good fit for storing large files inside MongoDB. But for scenarios with very heavy access or high bandwidth needs, solutions like a CDN or Amazon S3 may be a better choice.