繁体   English   中英

MongoDB总和增长

[英]MongoDB Aggregation Sum Growth

我有一个MondoDB聚合管道,通过汇总所有Sales来输出每日收入:

Sale.aggregate
    ([
        {
            $project: {
                day: { $substr: ['$createdAt', 0, 10], },
            },
        },
        {
            $group: {
                _id: '$day',
                earnings: { $sum: '$pricing.earnings' },
            },
        },
        {
            $sort: {
                _id: 1
            }
        },
        {
            $project: {
                date: '$_id',
                earnings: '$earnings',
            },
        },
        {
            $group: {
                _id: null,
                stats: { $push: '$$ROOT' },
            }
        },
        {
            $project: {
                stats: {
                    $map: {
                        // returns an array with all dates between 2 provided params
                        input: dates.daysArray(dates.getDay(user.createdAt), dates.today()),
                        as: 'date',
                        in: {
                            $let: {
                                vars: { index: { $indexOfArray: ['$stats._id', '$$date'] } },
                                in: {
                                    $cond: {
                                        if: { $ne: ['$$index', -1] },
                                        then: { $arrayElemAt: ['$stats', '$$index'] },
                                        else: { _id: '$$date', date: '$$date', earnings: 0 }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        {
            $unwind: '$stats'
        },
        {
            $replaceRoot: {
                newRoot: '$stats'
            }
        },
        {
            $project: {
                _id: 0,
                x: '$date',
                y: '$earnings',
            },
        },
    ])

该管道的输出可能如下所示:

[
    {
        x: '2019-01-09',
        y: 10,
    },
    {
        x: '2019-01-10',
        y: 5,
    },
    {
        x: '2019-01-11',
        y: 20,
    }
]

这意味着在2019-01-09有10美元的销售额,在2019-01-10 5美元的销售额, 2019-01-10

现在,我不想要每日收入,而是想要获得的所有收入的总和。 这意味着结果应如下所示:

[
    {
        x: '2019-01-09',
        y: 10, // a total of $10 on the first day
    },
    {
        x: '2019-01-10',
        y: 15, // a total of $15 on the second day (10 + 5)
    },
    {
        x: '2019-01-11',
        y: 35, // a total of $35 on the third day (15 + 20)
    }
]

所以基本上我不想要每日数量,而是增长。

PS:我正在使用此数据显示在图表中。

您可以在拥有的基础上添加以下阶段

逻辑是$push $arrayElemAt $push x和y $push到数组,使用$range按索引迭代数组,对于x在index处获取$arrayElemAt ,对于y $slice$sum直到index+1

db.t51.aggregate([
    {$group : {_id : null, x : {$push : "$x"}, y : {$push : "$y"}}},
    {$project : {data : {
        $map : { 
            input : {$range : [0, {$size : "$x"}]},
            as : "idx",
            in : { x : {$arrayElemAt : ["$x", "$$idx"]}, y : {$sum : {$slice : ["$y", {$sum : ["$$idx",1]}]}}}}
    }}},
    {$unwind : "$data"},
    {$replaceRoot: {newRoot : "$data"}}
]).pretty()

如果您有更多要汇总或预测的字段,则可以在以下阶段使用

db.t51.aggregate([
    {$group : {_id : null, data : {$push : "$$ROOT"}}}, 
    {$addFields : {data : 
        {$reduce : {
            input : "$data", 
            initialValue : [{y : 0}], 
            in : {$concatArrays : [ "$$value",[{$mergeObjects : ["$$this", { y : {$sum : ["$$this.y",{$arrayElemAt : ["$$value.y", -1]}]}}]}]]}
        }}
    }},
    {$addFields : {data : {$slice : ["$data", 1, {$size : "$data"}]}}},
    {$unwind : "$data"},
    {$replaceRoot: {newRoot : "$data"}}
]).pretty()

Aggregation Framework独立地处理所有文档(通过设计),因此它们彼此之间不了解。 更改的唯一方法是使用$ group _id设置为null可使您将所有文档中的数据捕获为一个。 然后,您可以遍历该数组(使用$ range获取索引数组,并使用$ map返回另一个数组)。 获得x$ arrayElemAt )很容易,对于y您需要使用$ reduce对所有数组元素求和。 $reduce的输入由$ slice运算符生成,并取决于索引(对于0 ,它将是[10] ,对于1 [10,5] ,依此类推)。 要完成查询,您需要$ unwind$ replaceRoot以获取原始文档形状。

db.col.aggregate([
    {
        $sort: { x: 1 }
    },
    {
        $group: {
            _id: null,
            xArr: { $push: "$x" },
            yArr: { $push: "$y" }
        }
    },
    {
        $project: {
            data: {
                $map: {
                    input: { $range: [ 0, { $size: "$xArr" } ] },
                    as: "i",
                    in: {
                        x: { $arrayElemAt: [ "$xArr", "$$i" ] },
                        y: {
                            $reduce: {
                                input: { $slice: [ "$yArr", { $add: [ "$$i", 1 ] } ] },
                                initialValue: 0,
                                in: { $add: [ "$$this", "$$value" ] }
                            }
                        }
                    }
                }
            }
        }
    },
    {
        $unwind: "$data"
    },
    {
        $replaceRoot: {
            newRoot: "$data"
        }
    }
])

我想您需要将上述步骤添加到现有聚合中。 为了证明它可以工作,可以将其运行为单独的集合:

db.col.save({ x: '2019-01-09', y: 10 })
db.col.save({ x: '2019-01-10', y: 5 })
db.col.save({ x: '2019-01-11', y: 20 })

它输出:

{ "x" : "2019-01-09", "y" : 10 }
{ "x" : "2019-01-10", "y" : 15 }
{ "x" : "2019-01-11", "y" : 35 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM