首页 > 解决方案 > 如何对列上的数据进行分组并在 MongoDB 上每小时汇总记录?

问题描述

我有一个集合如下

"InteractionId": "1e4ab424-e3ab-4cc1-8642-c37bb6248a09",
"ArticleType": "Article",
"TransactionDate": ISODate("2019-06-27T16:44:16.307+05:30")

请注意,“ArticleType”可以是不同的类型,现在我想获取 ArticleType 的每小时计数。

我已经尝试了一些查询,但没有奏效。

USER_INTERACTIONS1.aggregate([
  {
    $project: {
      _id: 0,
      ArticleType: "$ArticleType",
      datePartDay: {
        $concat: [
          { $substr: [{ $dayOfMonth: "$TransactionDate" }, 0, 2] },
          "-",
          { $substr: [{ $month: "$TransactionDate" }, 0, 2] },
          "-",
          { $substr: [{ $year: "$TransactionDate" }, 0, 4] }
        ]
      }
    }
  },

  {
    $group: {
      _id: { TransactionDate: "$datePartDay", ArticleType: "$ArticleType" },
      count: { $sum: 1 }
    }
  },
  { $sort: { _id: 1 } }
]);

标签: mongodb

解决方案


推荐阅读