假设我的文档如下所示:

[
  {
    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;
});

推荐答案

是的,这是最近使用版本5.0中引入的$setWindowFields阶段变得非常容易的,它允许我们对文档的"窗口"(在您的情况下是所有年份)进行计算,而在理论上也可以使用更老的操作符来做这件事,我建议不要这样做,因为不仅语法非常混乱,而且这样的查询的性能也将是糟糕的.只按年份分组,然后用一个简单的循环在代码中完成其余的操作会更容易.

无论如何,下面是如何做到这一点的:

db.collection.aggregate([
  {
    $group: {
      _id: "$year",
      sum: {
        $sum: 1
      }
    }
  },
  {
    $setWindowFields: {
      sortBy: {
        _id: -1
      },
      output: {
        sum: {
          $sum: "$sum",
          window: {
            documents: [
              "unbounded",
              "current"
            ]
          }
        }
      }
    }
  }
])

Mongo Playground

Mongodb相关问答推荐

如何使用ID数组对一个集合中的金额求和并更新另一个集合中的字段?

在提供的文档(_Id)之后和之前,是否有一个Mongo操作来获取已排序(和/或过滤)集合中的文档计数?

在不知道字段名称的情况下如何引用 MongoDB 中的字段?

Mongoose 查询以获取内部数组和该内部数组中的特定元素

我可以在 MongoDB 中将字段值设置为对象键吗?

Mongoose - $project 嵌套的对象数组到数组的根级别

如何在 MongoDB 中已经存在的 slug 中添加一个随机数?

使用 $addFields 将字段添加到 $lookup 结果中的每个项目

在 MongoDB 中打开连接的 SocketTimeout

如何构建我只需要打开一次 mongodb 连接的快速应用程序?

MongoDB获取聚合查询的executionStats

mongodb,pymongo,aggregate聚合给出奇怪的输出

使用 Node.js 和 mongodb 处理超时

django 和 mongodb 是否使迁移成为过go ?

如何使用 mongodb 和 php 正确处理分页查询?

如何解决 ClassNotFoundException:com.mongodb.connection.BufferProvider?

如何在mongoose中加入两个集合

Mongoose.js:嵌套属性的原子更新?

Mongoose / MongoDB 用户通知方案建议

如何在 Ubuntu 10.04 中使用 --auth 选项重新启动 mongodb?