- MongoEngine - Discussion
- MongoEngine - Useful Resources
- MongoEngine - Quick Guide
- MongoEngine - Extensions
- MongoEngine - Text Search
- MongoEngine - Signals
- MongoEngine - GridFS
- MongoEngine - Javascript
- MongoEngine - Atomic Updates
- MongoEngine - Document Inheritance
- MongoEngine - Advanced Queries
- MongoEngine - Aggregation
- MongoEngine - Indexes
- MongoEngine - Custom Query Sets
- MongoEngine - Sorting
- MongoEngine - QuerySet Methods
- MongoEngine - Query Operators
- MongoEngine - Filters
- MongoEngine - Querying Database
- MongoEngine - Add/Delete Document
- MongoEngine - Fields
- MongoEngine - Dynamic Schema
- MongoEngine - Document Class
- MongoEngine - Connecting to MongoDB Database
- MongoEngine - Installation
- MongoEngine - Object Document Mapper
- MongoEngine - MongoDB Compass
- MongoEngine - MongoDB
- MongoEngine - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
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 * 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