GridFS stands for Grid File System. MongoDB GridFS is a specification for storing and retrieving large files (such as images, videos, audio files, or any binary data) in MongoDB that exceed the BSON document size limit of 16 MB.
How It Works
GridFS uses two collections to manage files:
fs.files– Stores file metadata such as filename, upload date, size, and a unique ID.fs.chunks– Stores the actual file data in chunks, each linked to the parent file via an ObjectId.
Each chunk document in fs.chunks looks like this:
{
"_id": ObjectId("..."),
"files_id": ObjectId("..."), // reference to fs.files._id
"n": 0, // chunk sequence number
"data": BinData(...) // binary data
}
Example Flow
- You upload a large file.
- GridFS splits it into chunks (e.g., 255 KB each).
- Each chunk is stored in
fs.chunks. - Metadata about the file (like name, length, and MD5 hash) goes into
fs.files. - When you download or read the file, GridFS reassembles it in order.
Tools & Drivers
Most MongoDB drivers include built-in support for GridFS.
For example:
- Node.js:
GridFSBucketAPI in the officialmongodbdriver. - Python:
gridfsmodule inpymongo. - Mongo Shell: Some tools like
mongofileslet you work with GridFS directly.
How to Add (Upload) Images to GridFS Manually via Command Line
MongoDB provides a built-in tool called mongofiles for working with GridFS from the terminal.
You can use it to upload, list, download, or delete files in GridFS — no programming needed.
Step-by-Step Example
1. Make sure MongoDB is running
If you’re running MongoDB locally:
mongod
2. Open another terminal window
3. Use the mongofiles tool
Here’s the syntax:
mongofiles --db <database_name> put <filename>
Example — Upload an Image
Suppose you have a file named photo.jpg in your current folder.
Run this command:
mongofiles --db stud put "D:\IMG_1035.jpg"
Explanation:
--db=mydatabase→ stores file in themydatabasedatabaseput photo.jpg→ uploads the file into GridFS
After Uploading
If you open the MongoDB shell and connect to your database:
mongosh
use stud
Then check the collections:
show collections
You’ll see:
fs.files
fs.chunks
Now, you can inspect what’s inside:
db.fs.files.find().pretty()
You’ll get something like:
{
"_id": ObjectId("654240f57b7d9e47f1fce9b2"),
"length": 523424,
"chunkSize": 261120,
"uploadDate": ISODate("2025-11-01T12:00:00Z"),
"filename": "photo.jpg"
}
And in fs.chunks:
db.fs.chunks.find().limit(2).pretty()
Each document looks like:
{
"_id": ObjectId("654240f57b7d9e47f1fce9b3"),
"files_id": ObjectId("654240f57b7d9e47f1fce9b2"),
"n": 0,
"data": BinData(0,"/9j/4AAQSkZJRgABAQ...")
}
To Download the Image Back
If you want to download the file again from GridFS:
mongofiles --db stud put "D:\IMG_1035.jpg"
This will create a new file named photo.jpg in your current folder.
To Delete the Image
mongofiles --db stud delete "D:\IMG_1035.jpg"
| Command | Action |
|---|
mongofiles --db=mydb put file.jpg | Upload (store in GridFS) |
mongofiles --db=mydb list | List all stored files |
mongofiles --db=mydb get file.jpg | Download a file |
mongofiles --db=mydb delete file.jpg | Delete a file |
Full Example Workflow
Step 1 — Start MongoDB
mongod --dbpath "C:\data\db"
Step 2 — Upload a file
mongofiles --db=test put 1.png
Step 3 — List files in GridFS
mongofiles --db=test list
Step 4 — Download the file
mongofiles --db=test get 1.png
Step 5 — Delete it (optional)
mongofiles --db=test delete 1.png
5. GridFS vs. normal MongoDB documents
| Feature | Normal document | GridFS |
|---|---|---|
| Maximum BSON document size | 16 MB | Supports files larger than 16 MB |
| Storage | Document fields | File metadata and chunks |
| Best suited for | Structured data | Large files |
| Example | Student record | Student photograph or PDF |
Step-by-Step: Install Composer and Upload an Image to MongoDB Using PHP
This example uses XAMPP on Windows, Composer, and MongoDB\Driver\Manager to upload an image into MongoDB without GridFS.
Step 1: Check PHP in XAMPP
Start Apache in the XAMPP Control Panel.
Open Command Prompt and run:
C:\xampp\php\php.exe -v
Check whether the MongoDB extension is enabled:
C:\xampp\php\php.exe -m
Look for:
mongodb
If mongodb is missing, install the compatible MongoDB PHP extension first. Composer cannot install that native extension automatically.
Step 2: Install Composer
Official downloadDownload Composer for Windows (Composer-Setup.exe)
1. Run the installer
Open Composer-Setup.exe and follow the installation wizard.
2. Select PHP executable
If prompted, select:
C:\xampp\php\php.exe
3. Verify Composer
Close and reopen Command Prompt, then run:
composer --version
Composer should display its version.
Step 3: Create your PHP project
Open Command Prompt and execute these commands:
cd C:\xampp\htdocs
mkdir imageupload
cd imageupload
Your project location is now:
C:\xampp\htdocs\imageupload
Step 4: Install the MongoDB PHP library using Composer
Run this command inside the imageupload folder:
composer require mongodb/mongodb
Composer will download the MongoDB PHP library and its dependencies. It will create files and folders similar to these:
MongoDB Docs
+1
imageupload/
├── vendor/
│ └── autoload.php
├── composer.json
└── composer.lock
Verify the installation:
composer show mongodb/mongodb
Important: The MongoDB PHP extension must already be installed and enabled before Composer can install a compatible library version. Current library versions have specific PHP and extension requirements, so an older XAMPP installation may require a compatible version.
Manual
+1
Step 5: Enable the MongoDB PHP extension
Open this file:
C:\xampp\php\php.ini
Find the following line:
;extension=mongodb
If the correct MongoDB extension DLL is already installed in C:\xampp\php\ext, remove the semicolon:
extension=mongodb
Save the file and restart Apache.
Check the extension again:
C:\xampp\php\php.exe -m
You should see mongodb in the output. If the DLL is missing or incompatible, download the extension that matches your PHP version, architecture, and thread-safety configuration. See the official PHP MongoDB installation guide.
Manual
+1
Step 6: Create index.php
Create a file named index.php inside C:\xampp\htdocs\imageupload.
<!DOCTYPE html>
<html>
<head>
<title>MongoDB Image Upload</title>
</head>
<body>
<h2>Upload Image</h2>
<form action="upload.php" method="post"
enctype="multipart/form-data">
<input type="file" name="image"
accept="image/*" required>
<button type="submit">Upload Image</button>
</form>
</body>
</html>
Step 7: Create upload.php
This code uses MongoDB\Driver\Manager to connect to MongoDB and save the image as binary data.
<?php
require_once __DIR__ . '/vendor/autoload.php';
use MongoDB\Driver\Manager;
use MongoDB\Driver\BulkWrite;
use MongoDB\BSON\Binary;
if (
!isset($_FILES['image']) ||
$_FILES['image']['error'] !== UPLOAD_ERR_OK
) {
exit("Please select an image.");
}
$tmp = $_FILES['image']['tmp_name'];
$name = basename($_FILES['image']['name']);
$mime = mime_content_type($tmp);
$allowed = [
'image/jpeg',
'image/png',
'image/gif',
'image/webp'
];
if (!in_array($mime, $allowed, true)) {
exit("Only JPG, PNG, GIF and WEBP images are allowed.");
}
$data = file_get_contents($tmp);
try {
// Connect to MongoDB
$manager = new Manager("mongodb://localhost:27017");
// Create document
$bulk = new BulkWrite();
$bulk->insert([
'name' => $name,
'type' => $mime,
'image' => new Binary(
$data,
Binary::TYPE_GENERIC
)
]);
// Insert into stud database
$result = $manager->executeBulkWrite(
'stud.images',
$bulk
);
echo "Image uploaded successfully!";
} catch (Throwable $e) {
echo "Error: " .
htmlspecialchars($e->getMessage());
}
?>
Step 8: Run the project
- Start Apache in XAMPP.
- Start your MongoDB server.
- Open this URL in your browser:
http://localhost/imageupload/index.php - Select an image and click Upload Image.
Step 9: Check the image in MongoDB
Open mongosh:
use stud
db.images.find(
{},
{ name: 1, type: 1 }
)
The stud.images collection will contain documents with the filename, MIME type, and binary image data.
Note: This simple example stores the entire image in one MongoDB document, so it is suitable for small images. MongoDB documents have a 16 MiB size limit.
One useful distinction: MongoDB\Driver\Manager and MongoDB\BSON\Binary come from the native PHP extension. The Composer library is not strictly required for this low-level example, but installing it provides the vendor/autoload.php file used above.
Explanation above code
1. Include Composer autoload file
require_once __DIR__ . '/vendor/autoload.php';
require_onceloads a PHP file only once.__DIR__returns the directory path of the current PHP file.vendor/autoload.phpis generated by Composer and loads the required PHP libraries.
Purpose: Makes the required Composer packages available to your PHP program.
2. Import MongoDB classes
use MongoDB\Driver\Manager;
use MongoDB\Driver\BulkWrite;
use MongoDB\BSON\Binary;
| Class | Purpose |
|---|---|
Manager | Connects to the MongoDB server. |
BulkWrite | Creates database write operations, including inserts. |
Binary | Stores image bytes as BSON binary data. |
These classes are provided by the MongoDB PHP extension.
3. Check whether an image was uploaded
if (
!isset($_FILES['image']) ||
$_FILES['image']['error'] !== UPLOAD_ERR_OK
) {
exit("Please select an image.");
}
$_FILESis a PHP superglobal array containing information about uploaded files.$_FILES['image']refers to the file input namedimagein your HTML form.isset()checks whether the file entry exists.UPLOAD_ERR_OKmeans the upload completed without a PHP upload error.exit()stops program execution and displays the message.
Purpose: Prevents the program from processing a missing file or a failed upload.
4. Get the uploaded file details
$tmp = $_FILES['image']['tmp_name'];
$name = basename($_FILES['image']['name']);
tmp_nameis the temporary location where PHP stores the uploaded file.nameis the original filename provided by the user.basename()removes directory components from the filename.
For example:
Original filename: photo.jpg
Temporary path: C:\xampp\tmp\php1234.tmp
The temporary path is where PHP reads the image before storing it in MongoDB.
5. Detect the image MIME type
$mime = mime_content_type($tmp);
This function attempts to identify the file’s content type.
Examples:
| Image format | MIME type |
|---|---|
| JPG / JPEG | image/jpeg |
| PNG | image/png |
| GIF | image/gif |
| WEBP | image/webp |
The MIME type is stored in $mime for validation and later saved in MongoDB.
6. Define allowed image formats
$allowed = [
'image/jpeg',
'image/png',
'image/gif',
'image/webp'
];
This array contains the file types accepted by the program.
if (!in_array($mime, $allowed, true)) {
exit("Only JPG, PNG, GIF and WEBP images are allowed.");
}
in_array()checks whether$mimeexists in$allowed.trueenables strict comparison.- If the MIME type is not in the list,
exit()stops the program.
Purpose: Rejects files whose detected MIME type is not on the allowed list. For production use, also verify the image contents with getimagesize() and enforce a file-size limit.
7. Read the image into memory
$data = file_get_contents($tmp);
file_get_contents() reads the uploaded image’s bytes from the temporary file.
For example, if the user uploads photo.jpg, $data contains the binary contents of that image, not just its filename.
8. Connect to MongoDB
$manager = new Manager("mongodb://localhost:27017");
This creates a MongoDB Manager object.
mongodb://is the MongoDB connection scheme.localhostmeans the MongoDB server is running on the same computer.27017is the default MongoDB port.
Make sure the MongoDB server is running before executing this code.
9. Create a write operation
$bulk = new BulkWrite();
Creates a BulkWrite object that holds database write operations.
The next step adds an insert operation to it.
10. Create and insert the image document
$bulk->insert([
'name' => $name,
'type' => $mime,
'image' => new Binary(
$data,
Binary::TYPE_GENERIC
)
]);
This creates a MongoDB document with three fields:
| Field | Value | Purpose |
|---|---|---|
name | $name | Original image filename |
type | $mime | Image MIME type |
image | Binary(...) | Actual image data |
What does Binary do?
new Binary($data, Binary::TYPE_GENERIC)
$datacontains the image bytes.Binary::TYPE_GENERICspecifies the generic BSON binary subtype.
MongoDB can store binary data inside a document, so you do not need to save the image as a separate file on the server.
11. Execute the insert operation
$result = $manager->executeBulkWrite(
'stud.images',
$bulk
);
This sends the write operation to MongoDB.
studis the database name.imagesis the collection name.$bulkcontains the insert operation.
If the database or collection does not already exist, MongoDB can create it automatically when the insert succeeds.
12. Display the success message
echo "Image uploaded successfully!";
Displays a message after the insert operation completes without throwing an exception.
13. Handle errors
} catch (Throwable $e) {
echo "Error: " .
htmlspecialchars($e->getMessage());
}
Throwablecatches PHP errors and exceptions thrown inside thetryblock.$e->getMessage()retrieves the error message.htmlspecialchars()escapes HTML-sensitive characters before displaying the message.