Mongoose - 汇总和分组日期以进行过滤

Mongoose - aggregate and group dates for filtering

我在 mongoose 上进行数据聚合时遇到了一些问题。希望得到一些帮助。

这是我的数据库(最小化):

    {
        _id: 1,
        timestamp: 2018-05-27T22:02:07.837+00:00,
   },
   {
        _id: 2,
        timestamp: 2019-10-27T22:02:07.837+00:00,
    },
    {
        _id: 3,
        timestamp: 2019-12-27T22:02:07.837+00:00,
    },
    {
        _id: 4,
        timestamp: 2020-01-27T22:02:07.837+00:00,
    },
    {
        _id: 5,
        timestamp: 2020-02-27T22:02:07.837+00:00,
    },
    {
        _id: 6,
        timestamp: 2020-09-27T22:02:07.837+00:00,
    }

这是我的目标结构:

   [
      [2018,5],
      [2019,10],
      [2019,12],
      [2020,1],
      [2020,2],
      [2020,9]
    ]

目前我的代码是:

  Model.aggregate([
    { $group: { _id: "$year", months: { $addToSet: "$month" } } }
  ]);

Mongo Playground

但我觉得我离我想要达到的目标还很远。 将不胜感激一些见解,谢谢大家!!

5个小时后,我成功了。 解决方案: https://mongoplayground.net/p/gFpFiK8vjkk

db.collection.aggregate([
          { $group: { _id: { year: { $year: "$timestamp" }, month: { $month: "$timestamp" } }, total: { $sum: 1 } } },
          { $sort: { "_id.year": -1, "_id.month": -1 } },
  
])