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

时间:2020-09-05 01:22:40

标签: mongodb date mongoose aggregation

我在猫鼬上进行数据汇总时遇到一些问题。希望能有所帮助。

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

    {
        _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

但是我觉得我距离我要达到的目标还很遥远。 感谢您的见解,谢谢大家!

1 个答案:

答案 0 :(得分:1)

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 } },
  
])