Hello Coders,
This article will brief you about Storing the images in MongoDB via python code.
Dependencies
We will be using just 2 library dependencies, namely:
- GridFS
- 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']
- 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")
That's it for now.
Thanks for reading
Top comments (1)
Hello i have used your example, however my fs.files seems to lack some of the attributes shown in the original gridfs documentation. Do you have any guidance to include the metadata in the fs.files?
Best regards