How to Store Images in MongoDB

Tahseen Tauseef Feb 02, 2024
  1. The GridFS in MongoDB
  2. Store Images in MongoDB Using GridFS
  3. Store Images in MongoDB Using Python
How to Store Images in MongoDB

You may use a database to store pictures and other tiny images in a database table. Such picture files may be processed considerably more efficiently on a file server.

However, when image data is stored in a binary field, it is only accessible to applications that stream raw picture data to and from that field.

The MongoDB GridFS specification is a viable choice for storing considerably huge files in MongoDB. It ensures that the file is broken down into manageable bits and saved in a database.

The process for saving and retrieving binary files to and from MongoDB is explained in this article.

The GridFS in MongoDB

GridFS is a standard for storing and retrieving larger files than the 16 MB limit set by BSON. GridFS splits a file into sections or chunks and keeps each piece separate rather than storing it as a single document.

Store a metadata JSON document for each item in Couchbase, along with a tiny thumbnail picture at most.

That document contains information about that object in your application that you need immediately and reference purpose-built object storage such as S3, a file system, or HDFS. So, you will have the best of both worlds.

In this MongoDB tutorial, the problem of storing images in the MongoDB database is discussed in detail. Also, you will learn the different ways you can keep the image and efficiently retrieve the images from the MongoDB database.

Store Images in MongoDB Using GridFS

You can store the images in the MongoDB database by creating a schema with Mongoose. The schema is defined by creating a file, model.js.

The data type Buffer is used for storing the images in the database form of arrays.

There are three ways for storing the images:

  1. GridFS: Using GridFS API, you will be able to store large-sized images. This API helps you store the large file into small chunks (255KiB) and store it into separate documents in an "fs.chunks" collection.
  2. Inline: In this, smaller images (16MB) can be stored into MongoDB documents using binary data.
  3. Reference: In this, only image references are stored in the database, and you can also store images in API or some file system.

Because huge files are difficult for end-users to access, storing the binary files in a database makes it easier to distribute across numerous sites. It is worth noting that before saving photos in a database, you should consider the benefits.

Store Images in MongoDB Using Python

This section will discuss how to store images in MongoDB via Python.

You can use two libraries for this:

  1. GridFS

    It is a file system storing and retrieving extensive data such as photos, audio, and movies. In this case, there is a bias to store data in a MongoDB collection.

    In addition, it can store files larger than the 16MB scale limit.

  2. PyMongo

    The Python library PyMongo connects with the MongoDB database. Various functionality actions, such as retrieving results, writing and deleting data, and running the database, are available.

    If you do not have the PyMongo library installed, you may do so using the following command:

pip3 install pymongo

You may now use the library when it has been installed. But, first, import the library, connect to the server to use MongoDB in Python, and build a database to store the photographs.

from pymongo import MongoClient

connection = MongoClient("localhost", 27017)

database = connection['DB_NAME']

MongoDB operates on Port 27017 by default. You can specify any name for the database in DB_NAME.

The GridFS library stores the photos in the MongoDB database in the following phase.

import gridfs
#Create an object of GridFs for the above database.
fs = gridfs.GridFS(database)

#Define an image object with the location.
file = "C:/Users/user/Pictures/dog.jpeg"

with open(file, 'rb') as f:
    contents = f.read()

fs.put(contents, filename="file")

Storing Image - Code

The preceding code shows how to save photos in a MongoDB database using Python.

Output:

Storing Image - Output

  1. You can see that we successfully built the database images on the right-hand side of the output.
  2. The database has two sub-folders labeled fs.chunks and fs.files.
  3. The image was saved in the fs.files folder with ObjectID(('612727d8e71b2de49ac00734'), where you can view all image details such as _id, filename, md5, chunk size, length, and upload date.