This example shows how to use
gridfs to store large binary
objects (e.g. files) in MongoDB.
The API docs for
This blog post for some motivation behind this API.
We start by creating a
GridFS instance to use:
>>> from pymongo import MongoClient >>> import gridfs >>> >>> db = MongoClient().gridfs_example >>> fs = gridfs.GridFS(db)
Saving and Retrieving Data¶
>>> a = fs.put(b"hello world")
>>> fs.get(a).read() b'hello world'
In addition to putting a
str as a GridFS file, we can also
put any file-like object (an object with a
method). GridFS will handle reading the file in chunk-sized segments
automatically. We can also add additional attributes to the file as
>>> b = fs.put(fs.get(a), filename="foo", bar="baz") >>> out = fs.get(b) >>> out.read() b'hello world' >>> out.filename 'foo' >>> out.bar 'baz' >>> out.upload_date datetime.datetime(...)
The attributes we set in
put() are stored in the
file document, and retrievable after calling
get(). Some attributes (like
special and are defined in the GridFS specification - see that
document for more details.