DEV Community

loading...

Store images in MongoDB via Python

thenishant profile image ||Nishant|| ・1 min read

Hello Coders,

This article will brief you about Storing the images in MongoDB via python code.

This is what want to achieve:

Dependencies

We will be using just 2 library dependencies, namely:

  1. GridFS
  2. PyMongo

What is GridFS?

GridFS is the MongoDB specification for storing and retrieving large files such as images, audio files, video files, etc. It is kind of a file system to store files but its data is stored within MongoDB collections. GridFS has the capability to store files even greater than its document size limit of 16MB.

What is pymongo?

The PyMongo distribution contains tools for interacting with MongoDB database from Python. The bson package is an implementation of the BSON format for Python. The pymongo package is a native Python driver for MongoDB. The gridfs package is a gridfs implementation on top of pymongo.

Now to Code

  • Connect to MongoDB

To install pymongo: pip3 install pymongo

from pymongo import MongoClient

# Connect to the server with the hostName and portNumber.
connection = MongoClient("localhost", 27017)

# Connect to the Database where the images will be stored.
database = connection['DB_NAME']
Enter fullscreen mode Exit fullscreen mode
  • Store the Image in the MongoDB
import gridfs

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

#define an image object with the location.
file = "image-4.jpg"

#Open the image in read-only format.
with open(file, 'rb') as f:
    contents = f.read()

#Now store/put the image via GridFs object.
fs.put(contents, filename="file")

Enter fullscreen mode Exit fullscreen mode

That's it for now.
Thanks for reading

Discussion (0)

pic
Editor guide