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 products collection, to print details of document with name of product as TV, we use Name as keyword argument.

main.py

from mongoengine import *

con = connect('myDb')

class Product(Document):
   productID = IntField(required=True)
   name = StringField()
   price = IntField()
   
for product in Product.objects(name='TV'):
   print ('ID:',product.productID, 'Name:',product.name, 'Price:',product.price)

Output

Compile and run the above code and verify the output −

ID: 2 Name: TV Price: 50000

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

main.py

from mongoengine import *

con = connect('myDb')

class Product(Document):
   productID = IntField(required=True)
   name = StringField()
   price = IntField()
   
qset=Product.objects
for product in qset.filter(name='TV'):
   print ('ID:',product.productID, 'Name:',product.name, 'Price:',product.price)

Output

Compile and run the above code and verify the output −

ID: 2 Name: TV Price: 50000
Advertisements