【问题标题】:MongoDB Aggregate $group for two accumulated fieldsMongoDB Aggregate $group 用于两个累积字段
【发布时间】:2021-09-16 00:58:37
【问题描述】:

我有以下文件

{ 
   id: ObjectId,
   branch: ObjectId,
   name: "lorem ipsum",
   type: "Delivery",
   total: 10.5
},
{ 
   id: ObjectId,
   branch: ObjectId,
   name: "lorem ipsum 22",
   type: "Carry out",
   total: 7.5
}, 
.
.
.

我正在尝试计算每个订单type
每个分支的平均total 像这样的每个分支的预期结果

{
   branch: ObjectId,
   name: "lorem ipsum",
   deliveryAVG: 8.7,
   CarryOut: 6.9
}

有什么建议吗?

【问题讨论】:

    标签: node.js mongodb mongoose aggregation-framework aggregate


    【解决方案1】:

    您可以使用$group 两次按分支和类型聚合,然后使用$arrayToObject 将每种类型转换为新的对象键:

    db.collection.aggregate([
        {
            $group: {
                _id: {
                    branch: "$branch",
                    type: "$type"
                },
                avg: { $avg: "$total" },
                name: { $first: "$name" }
            }
        },
        {
            $group: {
                _id: "$_id.branch",
                name: { $first: "$name" },
                averages: {
                    $push: {
                        k: "$_id.type",
                        v: "$avg"
                    }
                }
            }
        },
        {
            $replaceRoot: {
                newRoot: {
                    $arrayToObject: {
                        $concatArrays: [ "$averages", [ { "k": "_id", "v": "$_id" }, { "k": "name", "v": "$name" } ] ]
                    }
                }
            }
        }
    ])
    

    Mongo Playground

    【讨论】:

    • 我收到这个错误“$concat 只支持字符串,不支持数组”
    • @MohammadShehab 已修复,它应该是 $concatArrays,请参阅操场
    • 假设我有分支的名称而不仅仅是 id 如何在最终结果中保存它
    猜你喜欢
    • 2019-05-24
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    • 2018-12-19
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多