假设我的文档如下所示:
[
{
name: "Example 1",
year: "2012"
},
{
name: "Example 2",
year: "2012"
},
{
name: "Example 3",
year: "2013"
},
{
name: "Example 4",
year: "2014"
}
]
使用aggregation,有没有办法达到group by year and sum the document count,但额外增加了add the sum of all later years?
我想要的result美元是:
[
{
_id: "2012",
count: 4 // years 2012-2014
},
{
_id: "2013",
count: 2 // years 2013-2014
},
{
_id: "2014",
count: 1 // only year 2014
}
]
现在,我使用的是普通的$group
+$sum
,它让我分别计算出每一年的计数,然后用JavaScript对它们进行排序.我希望有一种更简单的方法来消除额外的JS代码:
yearCounts: [
{ $group: { _id: "$year", count: { $sum: 1 } } }
]
const yearCounts: { _id: string, count: number }[] = aggregationResult[0].yearCounts || [];
const yearCountsSummed = yearCounts.map((yearCount: { _id: string, count: number }) => {
const yearsUntil = yearCounts.filter(year => year._id >= yearCount._id);
const countSummed = yearsUntil.map(yearCount => yearCount.count).reduce((a, b) => a + b) || 0;
return countSummed;
});