How to Download File from MongoDB Using GridFS
To download a file from MongoDB, use
GridFS, which stores files in chunks. You retrieve the file by opening a download stream with GridFSBucket.openDownloadStream() and then save or process the data as needed.Syntax
MongoDB uses GridFS to store and retrieve files larger than 16MB. The main method to download a file is openDownloadStream(fileId), which returns a readable stream of the file's data.
GridFSBucket: The class to interact with files in GridFS.openDownloadStream(fileId): Opens a stream to read the file by its uniquefileId.- The stream can be piped to a file or processed in your application.
javascript
const { MongoClient, ObjectId, GridFSBucket } = require('mongodb'); // Connect to MongoDB const client = new MongoClient(uri); await client.connect(); const db = client.db('yourDatabase'); // Create GridFS bucket const bucket = new GridFSBucket(db); // Open download stream by file ID const downloadStream = bucket.openDownloadStream(new ObjectId('yourFileId')); // Pipe stream to a writable destination (e.g., file system) downloadStream.pipe(destinationStream);
Example
This example shows how to download a file from MongoDB GridFS and save it to the local file system using Node.js.
javascript
const { MongoClient, ObjectId, GridFSBucket } = require('mongodb'); const fs = require('fs'); async function downloadFile() { const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri); try { await client.connect(); const db = client.db('myfilesdb'); const bucket = new GridFSBucket(db); const fileId = new ObjectId('64a1f2b5e4b0c123456789ab'); // Replace with your file's ObjectId const downloadStream = bucket.openDownloadStream(fileId); const writeStream = fs.createWriteStream('./downloaded_file'); downloadStream.pipe(writeStream); writeStream.on('finish', () => { console.log('File downloaded successfully'); client.close(); }); downloadStream.on('error', (error) => { console.error('Error downloading file:', error); client.close(); }); } catch (err) { console.error('Connection error:', err); } } downloadFile();
Output
File downloaded successfully
Common Pitfalls
- Wrong file ID: Using an incorrect or string ID instead of
ObjectIdcauses errors. - Not handling streams: Forgetting to listen for
errororfinishevents can cause silent failures. - Missing GridFSBucket: Trying to download files without initializing
GridFSBucketproperly. - Large files: Attempting to load entire file into memory instead of streaming can cause crashes.
javascript
/* Wrong way: Using string instead of ObjectId */ const downloadStream = bucket.openDownloadStream('64a1f2b5e4b0c123456789ab'); // Incorrect /* Right way: Use ObjectId */ const downloadStream = bucket.openDownloadStream(new ObjectId('64a1f2b5e4b0c123456789ab'));
Quick Reference
Remember these key points when downloading files from MongoDB:
| Action | Description |
|---|---|
| Initialize GridFSBucket | Use new GridFSBucket(db) to work with files. |
| Use ObjectId for file | Always convert file ID string to ObjectId. |
| Open download stream | Call openDownloadStream(fileId) to get file data stream. |
| Handle stream events | Listen for error and finish to manage flow. |
| Pipe to destination | Pipe the stream to a file or response to save or send the file. |
Key Takeaways
Use GridFSBucket and openDownloadStream with ObjectId to download files from MongoDB.
Always handle stream events like error and finish to avoid silent failures.
Pipe the download stream directly to a writable destination to efficiently save large files.
Ensure the file ID is a valid ObjectId, not a plain string.
Initialize GridFSBucket with the correct database before downloading files.