我有一个 MongoDB 查询如下:
data = db.collection.aggregate([{"$match":{"created_at":{"$gte":start,"$lt":end}}},{"$group":{"_id":"$stage","count":{"$sum":1}}},{"$match":{"count":{"$gt":m{u'count': 296, u'_id': u'10.57.72.93'}
结果如下:
{u'count': 230, u'_id': u'111.11.111.111'}
{u'count': 2240, u'_id': u'111.11.11.11'}
我正在尝试按“计数”列对输出进行排序:
data.sort('count', pymongo.DESCENDING)
...但我收到以下错误:
'CommandCursor' object has no attribute 'sort'
谁能解释这个错误的原因?
最佳答案
使用 $sort
,如 Aggregation example 所示:
from bson.son import SON
data = db.collection.aggregate([
{"$match":{"created_at":{"$gte":start,"$lt":end}}},
{"$group":{"_id":"$stage","count":{"$sum":1}}},
{"$match":{"count": ... }},
{"$sort": SON([("count", -1)])} # <---
])
替代通用解决方案:使用 sorted
具有自定义键功能:
data = db.collection.aggregate(...)
data = sorted(data, key=lambda x: x['count'], reverse=True)
关于python - 对 PyMongo 查询的结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36566166/