MongoEngine – Filters

MongoEngine – Filters

The objects attribute is a QuerySet manager. It creates and returns a QuerySet when accessed. A query can be subjected to filter with the help of field names as keyword arguments. For example, from above books collection, to print details of document with id of book is 1003, we use book_id as keyword argument.

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()
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(book_id=1003):
print('ID:', book.book_id, 'Name:',
book.book_name, 'Price:', book.book_price)

You can use filter method of QuerySet object to apply filter to query. Following code snippet also returns product details with book_id = 1003

from enum import unique
from mongoengine import connect
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()
def _init__(self, book_id, book_name, book_price):
self.book_id = book_id
self.book_name = book_name
self.book_price = book_price
qset = Books.objects
for book in qset.filter(book_id=1003):
print('ID:', book.book_id, 'Name:',
book.book_name, 'Price:', book.book_price)

it will give following output:

ID: 1003 Name: Machine Learning Price: 1000.00
MongoEngine – Querying Database (Prev Lesson)
(Next Lesson) MongoEngine – Query Operators
', { 'anonymize_ip': true });