MongoEngine – Advanced Queries

MongoEngine – Advanced Queries

In order to get more efficiency in retrieving a subset of fields in a document, use only() method of Objects attribute. This will significantly improve performance especially for fields with extremely large length such as ListField. Pass the required field to only() function. If other fields are accessed after executing only() query, default value is returned.

from mongoengine import connect
from mongoengine import StringField, IntField, Document, DecimalField
connect('mydata', host='mongodb://localhost/mydata')
class Books(Document):
book_id = IntField(unique=True, required=True)
book_name = StringField(max_length=50)
book_price = DecimalField()
status = StringField(default='Available')
doc = Books.objects.only('book_name').first()
print('Name:', doc.book_name)
print('Status:', doc.status)
print('Price:', doc.book_price)

Output

Name: let us C
Status: Available
Price: None

Note − The value of status attribute is used as default. As default is not specified for book_price, it prints None.
You may call reload() function if you need missing fields.
When a document class has a ListField or DictField, while iterating through it, any DBREf objects are automatically dereferenced. To increase the efficiency further, especially if the document has ReferenceField, number of queries can be limited by using select_related() function which converts QuerySet in a list and effects dereferencing.

MongoEngine – Indexes (Prev Lesson)
(Next Lesson) MongoEngine – Document Inheritance