MongoEngine - Sorting



QuerySets order_by() function is used to obtain the query result in a sorted manner. The usage is as follows −

Qset.order_by(fieldname)

By default, the sort order is ascending. For descending order, attach sign to name of field. For example, to get price wise list in ascending order −

main.py

from mongoengine import *

con = connect('myDb')

class Product(Document):
   productID = IntField(required=True)
   name = StringField()
   price = IntField()
   
for product in Product.objects.order_by('price'):
   print ("Name:{} price:{}".format(product.name, product.price))

Output

Name:Router price:2000
Name:Scanner price:5000
Name:Printer price:12500
Name:Laptop price:25000
Name:TV price:50000

Following code will get the list in descending order of name −

main.py

from mongoengine import *

con = connect('myDb')

class Product(Document):
   productID = IntField(required=True)
   name = StringField()
   price = IntField()
   
for product in Product.objects.order_by('-name'):
   print ("Name:{} price:{}".format(product.name, product.price))

Output

Name:TV price:50000
Name:Scanner price:5000
Name:Router price:2000
Name:Printer price:12500
Name:Laptop price:25000

You can also get sorting done on multiple fields. This code will get you namewise, pricelist in ascending order.

main.py

from mongoengine import *

con = connect('myDb')

class Product(Document):
   productID = IntField(required=True)
   name = StringField()
   price = IntField()
   
for product in Product.objects.order_by('name','price'):
   print ("Name:{} price:{}".format(product.name, product.price))

Output

Name:Laptop price:25000
Name:Printer price:12500
Name:Router price:2000
Name:Scanner price:5000
Name:TV price:50000
Advertisements