You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Pymongo的aggregate命令对字典数组按size排序?

使用MongoDB聚合对数组内元素按size降序排序(Pymongo实现)

针对你的需求,有两种聚合方案可以实现files数组按size降序排列,以下是具体实现:

方案一:使用$sortArray(MongoDB 3.2+ 推荐)

这是最简洁高效的方式,直接通过聚合操作排序数组,无需拆分数组元素:

from pymongo import MongoClient

# 连接数据库
client = MongoClient()
db = client["users"]
coll = db["你的集合名称"]

# 聚合管道
pipeline = [
    # 可选:匹配目标文档(如果只需要处理特定文档,比如指定_id)
    {"$match": {"_id": "xxx"}},
    # 对files数组按size字段降序排序,替换原files字段
    {"$addFields": {
        "files": {
            "$sortArray": {
                "input": "$files",
                "sortBy": {"size": -1}  # -1表示降序,1为升序
            }
        }
    }},
    # 可选:只输出排序后的files数组,隐藏其他字段
    {"$project": {"files": 1, "_id": 0}}
]

# 执行聚合并获取结果
result = list(coll.aggregate(pipeline))
# 输出排序后的数组
print(result[0]["files"])

方案二:兼容旧版本MongoDB(3.2之前)

如果你的MongoDB版本较低,不支持$sortArray,可以用$unwind+$sort+$group的组合:

from pymongo import MongoClient

client = MongoClient()
db = client["users"]
coll = db["你的集合名称"]

pipeline = [
    {"$match": {"_id": "xxx"}},
    # 将files数组拆分为单个文档
    {"$unwind": "$files"},
    # 按files.size降序排序
    {"$sort": {"files.size": -1}},
    # 重新将元素聚合为files数组
    {"$group": {
        "_id": "$_id",
        "files": {"$push": "$files"}
    }},
    {"$project": {"files": 1, "_id": 0}}
]

result = list(coll.aggregate(pipeline))
print(result[0]["files"])

两种方案对比

  • $sortArray方案:性能更优,无需拆分数组,代码更简洁,适合MongoDB 3.2及以上版本。
  • 旧版本兼容方案:兼容性强,但拆分数组会生成临时文档,数据量较大时性能稍逊。

内容的提问来源于stack exchange,提问作者Tasos500

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 03:01:21