Inserting Data File in MongoDB

Anyway, here’s a simple example. Of course change the URI and filename to suit.

from pymongo import MongoClient
import gridfs

client = MongoClient("mongodb+srv://myid:mYpAsSw0rD@cluster0-foo.mongodb.net")
db = client.test
bucket = gridfs.GridFSBucket(db)

with open("myfile.txt", "rb") as f:
    bucket.upload_from_stream("myfile", f)
client.close()
3 Likes