访问 MongoDB 聚合结果中的上一个文档

Access to previous document in MongoDB aggregation result

问题是如何从结果集中引用之前的文档?
我有一个这样的结果的聚合:

var result = db.collection.aggregate([...])

{
    "_id" : "2018-01",
    "month" : "2018-01",
    "count" : 283.0
}
{
    "_id" : "2018-02",
    "month" : "2018-02",
    "count" : 260.0
}
{
    "_id" : "2018-03",
    "month" : "2018-03",
    "count" : 287.0
}
{
    "_id" : "2018-04",
    "month" : "2018-04",
    "count" : 264.0
}
{
    "_id" : "2018-05",
    "month" : "2018-05",
    "count" : 292.0
}

目标是获取本月计数与上个月计数之间的差异。所以要得到这样的结果:

{
    "_id" : "2018-01",
    "month" : "2018-01",
    "count" : 283.0,
    "difference" : 283.0
}
{
    "_id" : "2018-02",
    "month" : "2018-02",
    "count" : 260.0,
    "difference" : -23.0
}
{
    "_id" : "2018-03",
    "month" : "2018-03",
    "count" : 287.0,
    "difference" : 17.0
}

如果您提供文档方案和您使用的聚合,我们可能会在整个过程中做到这一点"dynamically",这样会更容易提供帮助。

话虽如此,我们可以在您当前聚合的末尾添加 2 个步骤。

首先(假设您的结果不在数组中)我们将对它们进行分组以便我们可以遍历数组:

{
  $group: {
    _id: null,
    temp: {$push: "$$ROOT"}
  }
},
{ 
   "$project" : {
       _id: 0,
       "temp_field" : {
            "$reduce" : {
                "input" : "$temp", 
                 "initialValue" : {
                     "prev" : 0.0, 
                     "results" : []
                 }, 
                 "in" : {
                    "prev" : "$$this.count", 
                     "results" : {
                        "$concatArrays" : ["$$value.results", 
                                    [
                                        {
                                            "month" : "$$this.month", 
                                            "_id" : "$$this._id"
                                            "count" : "$$this.count", 
                                            "diff" : {
                                                "$subtract" : [
                                                    "$$this.count", 
                                                    "$$value.prev"
                                                ]
                                            }
                                        }
                                    ]
                                ]
                            }
                        }
                    }
                }
            }
        },

最后我们只需要"restore"旧的结果格式:

{
   $unwind: "$temp_field"
},
{
   $project: {
      _id: "$temp_field.results._id",
      count: "$temp_field.results.count",
      month: "$temp_field.results.month",
      difference: "$temp_field.results.diff"
   }
}

*** 注意: 我实际上并没有正确计算差异(按值将一个月与前一个月相匹配),这意味着如果您缺少月份,您应该事先处理好。以及提前按日期对数组进行排序,因为我只是使用数组中的前一个进行减法。