访问MongoDB聚合结果中的上一个文档
问题是如何从结果集中引用上一个文档?访问MongoDB聚合结果中的上一个文档,mongodb,aggregate,window-functions,Mongodb,Aggregate,Window Functions,问题是如何从结果集中引用上一个文档? 我有这样一个结果: 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", "mo
我有这样一个结果:
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
}
如果您提供您所使用的文档方案和聚合,那么将更容易提供帮助,因为我们可能能够在整个过程中“动态”地完成这项工作 话虽如此,我们只需在当前聚合的末尾添加两个步骤 首先(假设您的结果不在数组中),我们将对它们进行分组,以便在数组中进行迭代:
{
$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"
]
}
}
]
]
}
}
}
}
}
},
最后,我们只需要“恢复”旧的结果格式:
{
$unwind: "$temp_field"
},
{
$project: {
_id: "$temp_field.results._id",
count: "$temp_field.results.count",
month: "$temp_field.results.month",
difference: "$temp_field.results.diff"
}
}
***注:
实际上,我并没有正确地计算差异(将一个月与前一个月的值进行匹配),这意味着如果您缺少几个月,您应该提前处理。以及提前按日期对数组进行排序,因为我只使用数组中的前一个进行减法