English 中文(简体)
MongoEngine - Advanced Queries
  • 时间:2024-11-05

MongoEngine - Advanced Queries


Previous Page Next Page  

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 *
con=connect( newdb )
class person (Document):
name=StringField(required=True)
city=StringField(default= Mumbai )
pin=IntField()
p1=person(name= Himanshu , city= Delhi , pin=110012).save()
doc=person.objects.only( name ).first()
print ( name: ,doc.name)
print ( city: , doc.city)
print ( PIN: , doc.pin)

Output


name: Himanshu
city: Mumbai
PIN: None

Note − The value of city attribute is used as default. As default is not specified for PIN, 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 pmited by using select_related() function which converts QuerySet in a pst and effects dereferencing.

MongoEngine API contains Q class which is useful for constructing advanced queries consisting of number of constraints. Q represents a part of query which can be initiapzed by keyword argument syntax and binary & and | operators.


person.objects(Q(name__startswith=’H’) &Q(city=’Mumbai’))
Advertisements