MongoEngine – GridFS

MongoEngine – GridFS

In MongoDB, the files with size larger than 16 MB are stored using GridFS specifications. A file is divided into multiple chunks each with a default size of 255KB. Large chunk may be as large as necessary. GridFS uses two collections, one for chunks and other for metadata.
GridFS may be used to store any file if you want to access it without having to load it entirely in the memory.
MongoEngine API supports GridFS through FileField object. Using this object, it is possible to insert and retrieve data. The FileField object’s put() method helps writing the file as a part of Document.

from mongoengine import connect
from mongoengine import StringField, IntField, Document, DecimalField, ListField
connect('mydata', host='mongodb://localhost/mydata')
class Animal (Document):
name=StringField()
type=StringField()
image=FileField()
a1=Animal()
a1.type="Mammal"
f=open('dog.png','rb')
a1.image.put(f,content_type='image/png')
a1.save()

Contents of FileField can be retrieved by read() method of Python’s File object.

image = a1.image.read()

There is also delete() method to delete the stored file.

a1 = name.objects(name='Dog').first()
a1.image.delete()
a1.save()

Note that the FileField stores only the ID of file in a separate GridFS collection. Hence delete() method does not delete the file physically.
The replace() method helps in replacing reference of file with another file.

a1 = name.objects(name='Dog').first()
f=open('newImg.png','rb')
a1.image.replace(f,content_type='image/png')
a1.save()
MongoEngine – Javascript (Prev Lesson)
(Next Lesson) MongoEngine – Signals
', { 'anonymize_ip': true });