Skip to content

Store images in the MongoDB database AQSA Spark By {Examples}

  • by

How to store images in the document of the MongoDB database collection? In this article, we will explore how to store images in a MongoDB database using binary data. There are multiple ways to store images in a MongoDB database. Here are some of them.

For each of them, we have separated collections according to the need of the method we are using.

1. Using Binary Data

One way to store images in a MongoDB database is to convert the image to binary data and store them as a Binary data type. This method involves reading the image file as bytes and storing it as a Binary object.

For example, we inserted a document into the student collection with a field filename that has a file StudentImage.png and an image_data field that uses the BinData constructor to store the image bytes as binary data.

# Conversion of images to binary data
db.student.insertOne({
filename: ‘StudentImage.png’,
image_data: BinData(0, ‘0A020F0B’)
});

The above document is represented as below in MongoDB.

2. Using URL Linking

With this, you can store images outside the database and store their URLs in a MongoDB document. By using this approach, we can reduce database size but may require additional setup and maintenance to ensure that the image links remain valid.

For example, we have inserted a new document into the student collection by first declaring the variable image that is stored with the filename field and the url field. The filename field is specified with the image file as StudentImage.png and the url field is specified with the URL link of that image. 

#Storing Image URLs
db.createCollection(‘student’)
const image = {
filename: ‘StudentImage’,
url: ‘https://studentPortal.com/images/StudentImage.jpg’
};
db.student.insertOne(image)
db.student.find()

After that, the image variable is inserted into the collection student using the insertOne() method which successfully stored the URL link of the file into the collection.

The output verified that the URL link is stored inside the collection.

3. Using Base64 Encoding

Another way to store images in a MongoDB database is to encode them in Base64 and store the encoded string as a field in a document. This approach is useful for smaller images or images that are viewed frequently, but it is less effective than storing binary data or using GridFS.

For example, we first use the fs module to read the image as a buffer. The file path is specified in the readFileSync() method of fs.

#encoding images in Base64
const fs = require(‘fs’);
const imageBuffer = fs.readFileSync(‘G:MyImage.png’);

After that, we convert the image buffer to a Base64-encoded string using the toString() method with the base64 encoding option.

#converting image buffer to a Base64-encoded string
const base64Image = imageBuffer.toString(‘base64’);

Then, using the insert command, we inserted the Base64-encoded image into the student collection.

#Inserting Base64-encoded image to collection
db.student.insertOne({ image: base64Image });

The output shows the Base64-encoded image string stored in the new document.

Now, we queried the documents below that contain a specific image by searching for the corresponding Base64-encoded string.

#Usage of find() method
db.student.find({ image: base64Image });

4. Using GridFS

Moreover, using the GridFS MongoDB’s GridFS is a file storage system that allows us to store large files, including images.

For example, in the initial step, we stored the specific image in the bucket by using the following MongoDB query. Here, we have created the file object that is specified with metadata for the image file StudentImage.png.

#storing the specific image in the bucket
var file = {
filename: ‘StudentImage.png’,
contentType: ‘image/png’,
metadata: { myKey: ‘myValue’ }
};

Next, we read the contents of the image file from the disk using the fs.readFileSync() method. Then, creates a new ObjectId that is used to identify the image file specifically.

#Usage of fs.readFileSync() method
var data = fs.readFileSync(‘G:StudentImage.png’);
var id = new ObjectId();

In the next stage, we declare the chunkSizeBytes variable, which is the size in bytes for each chunk of the image file data. Here, it is set to 244.

#Declaration of chunkSizeBytes variable
var chunkSizeBytes = 1024 * 244;
var chunks = [];

Then, we loop over the binary data buffer in chunks of chunkSizeBytes bytes and generate an array chunk that contains an object for each chunk.

#Usage of for loop
for (var i = 0; i < data.length; i += chunkSizeBytes) {
chunks.push({
files_id: id,
n: i / chunkSizeBytes,
data: data.slice(i, i + chunkSizeBytes)
});
}

Now, in the following query, we insert the file object into the fs.files collection.

#inserting file object into the fs.files collection
db.fs.files.insert({
_id: id,
length: data.length,
chunkSize: chunkSizeBytes,
uploadDate: new Date(),
metadata: file.metadata,
filename: file.filename,
contentType: file.contentType
});

The output verifies the insertion of the image file object into the fs.files collection.

In the end, we insert the chunks array into the fs.chunks collection.

#Inserting chunks array
db.fs.chunks.insert(chunks);

There is the output for the above execution.

More details about GridFS can be found here.

5. Conclusion

Wrap up, exploring the effective approaches to store images in the MongoDB database. Regardless of the method used, it is important to optimize image storage and retrieval to ensure that database performance is not negatively impacted.

 How to store images in the document of the MongoDB database collection? In this article, we will explore how to store images in a MongoDB database using binary data. There are multiple ways to store images in a MongoDB database. Here are some of them. For each of them, we have separated collections according to  Read More MongoDB 

Leave a Reply

Your email address will not be published. Required fields are marked *