- MongoEngine 教程
- MongoEngine - 主页
- MongoEngine - MongoDB
- MongoEngine - MongoDB Compass
- MongoEngine - 对象文档映射器
- MongoEngine - 安装
- MongoEngine - 连接到 MongoDB 数据库
- MongoEngine - 文档类
- MongoEngine - 动态模式
- MongoEngine - 字段
- MongoEngine - 添加/删除文档
- MongoEngine - 查询数据库
- MongoEngine - 过滤器
- MongoEngine - 查询操作符
- MongoEngine - QuerySet 方法
- MongoEngine - 排序
- MongoEngine - 自定义查询集
- MongoEngine - 索引
- MongoEngine - 聚合
- MongoEngine - 高级查询
- MongoEngine - 文档继承
- MongoEngine - 原子更新
- MongoEngine - Javascript
- MongoEngine - GridFS
- MongoEngine - 信号
- MongoEngine - 文本搜索
- MongoEngine - 扩展
- MongoEngine 有用资源
- MongoEngine - 快速指南
- MongoEngine - 有用资源
- MongoEngine - 讨论
MongoEngine - 排序
QuerySet 的 order_by() 函数用于以已排序的方式获取查询结果。使用方法如下 -
Qset.order_by(‘fieldname’)
默认情况下,排序顺序为升序。对于降序,请在字段名称后面添加 - 符号。例如,要以升序获取按价格排序的列表 -
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))
输出
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:Philips price:31000 Name:Laptop company:Dell price:45000 Name:TV company:Samsung price:50000
以下代码将按姓名降序获取列表 -
for product in products.objects.order_by('-Name'): print ("Name:{} company:{} price:{}".format(product.Name, product.company, product.price))
输出
Name:TV company:Samsung price:50000 Name:TV company:Philips 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
你还可以对多个字段进行排序。此代码将按公司、价格列表升序获取结果。
for product in products.objects.order_by('company','price'): print ("Name:{} company:{} price:{}".format(product.Name, product.company, product.price))
输出
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:Philips price:31000 Name:TV company:Samsung price:50000
广告