MongoEngine – QuerySet Methods

MongoEngine – QuerySet Methods

The QuerySet object possesses following useful methods for querying the database.

first()

First document satisfying the query is returned. Following code will return first document in Books collection, that has price 1000 are returned. This method is now the default document query and objects attribute of products class returns filtered documents.

from mongoengine import connect
from mongoengine import StringField, IntField, Document, DecimalField, queryset_manager
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()
def _init__(self, book_id, book_name, book_price):
self.book_id = book_id
self.book_name = book_name
self.book_price = book_price
@queryset_manager
def expensive_prods(docs_cls, queryset):
return queryset.filter(book_price__gt=1000)
for book in Books.expensive_prods():
print("book-id:{}tt book_name: {}tt price:{}".format(
book.book_id, book.book_name, book.book_price))

Output

book-id:1004             book_name: Data Structure               price:1300.00
book-id:1005             book_name: Data Structure & Algorithm           price:1240.70
book-id:1006             book_name: Data Science                 price:1600.00
book-id:1007             book_name: Data Analysis and Algorithm          price:1680.00

If you wish to customize methods for filtering documents, first declare a subclass of QuerySet class, and use it as value of queryset_class property in meta dictionary.
The example below uses MyQuerySet class as definition of custom queryset. The myqrymethod() in this class filters the documents whose name field ends with ‘hm’. In Books class, meta attribute refers to this queryset subclass is used as value of queryset_class property.

from mongoengine import connect
from mongoengine import StringField, IntField, Document, DecimalField, QuerySet
connect('mydata', host='mongodb://localhost/mydata')
class MyQuerySet(QuerySet):
def myqrymethod(self):
return self.filter(book_name__endswith='hm')
class Books(Document):
meta = {'queryset_class': MyQuerySet}
book_id = IntField(unique=True, required=True)
book_name = StringField(max_length=50)
book_price = DecimalField()
def _init__(self, book_id, book_name, book_price):
self.book_id = book_id
self.book_name = book_name
self.book_price = book_price
for book in Books.objects.myqrymethod():
print("Book_id : {} Book_name : {} price : {}".format(
book.book_id, book.book_name, book.book_price))

Output

Book_id : 1005 Book_name : Data Structure & Algorithm price : 1240.70
Book_id : 1007 Book_name : Data Analysis and Algorithm price : 1680.00
MongoEngine – Advanced Queries (Prev Lesson)
(Next Lesson) MongoEngine – Document Inheritance
', { 'anonymize_ip': true });