MongoEngine Tutorial
Selected Reading
- 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 - Sorting
MongoEngine - Sorting
QuerySet’s 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 pst in ascending order −
from mongoengine import * con=connect( newdb ) class products (Document): ProductID=IntField(required=True) company=StringField() Name=StringField() price=IntField() for product in products.objects.order_by( price ): print ("Name:{} company:{} price:{}".format(product.Name, product.company, product.price))
Output
Name:Router company:Iball price:2000 Name:Scanner company:Cannon price:5000 Name:Printer company:Cannon price:12500 Name:Laptop company:Acer price:25000 Name:TV company:Phipps price:31000 Name:Laptop company:Dell price:45000 Name:TV company:Samsung price:50000
Following code will get the pst in descending order of name −
for product in products.objects.order_by( -Name ): print ("Name:{} company:{} price:{}".format(product.Name, product.company, product.price))
Output
Name:TV company:Samsung price:50000 Name:TV company:Phipps price:31000 Name:Scanner company:Cannon price:5000 Name:Router company:Iball price:2000 Name:Printer company:Cannon price:12500 Name:Laptop company:Acer price:25000 Name:Laptop company:Dell price:45000
You can also get sorting done on multiple fields. This code will get you companywise, pricepst in ascending order.
for product in products.objects.order_by( company , price ): print ("Name:{} company:{} price:{}".format(product.Name, product.company, product.price))
Output
Name:Laptop company:Acer price:25000 Name:Scanner company:Cannon price:5000 Name:Printer company:Cannon price:12500 Name:Laptop company:Dell price:45000 Name:Router company:Iball price:2000 Name:TV company:Phipps price:31000 Name:TV company:Samsung price:50000Advertisements