Mongodb - 获取每小时销售额

Mongodb - Get sales per hours

好人!我需要你的帮助。

我正在尝试使用 apexcharts 和从 Mongodb 导入的数据创建折线图。 我正在尝试绘制每小时销售额的图表,因此我需要一天中每个小时的销售额。

示例 Mongodb 文档。

{
    "_id" : ObjectId("5dbee4eed6f04aaf191abc59"),
    "seller_id" : "5aa1c2c35ef7a4e97b5e995a",
    "temp" : "4.3",
    "sale_type" : "coins",
    "createdAt" : ISODate("2020-05-10T00:10:00.000Z"),
    "updatedAt" : ISODate("2019-11-10T14:32:14.650Z")
}

到目前为止,我有这样的查询:

    db.getCollection('sales').aggregate([
          { "$facet": {
            "00:00": [
              { "$match" : {createdAt: {$gte: ISODate("2020-05-10T00:00:00.000Z"),$lt: ISODate("2020-05-10T00:59:00.001Z")},seller_id: "5aa1c2c35ef7a4e97b5e995a",
        }},
              { "$count": "sales" },
            ],
            "01:00": [
              { "$match" : {createdAt: {$gte: ISODate("2020-05-10T01:00:00.000Z"),$lt: ISODate("2020-05-10T01:59:00.001Z")},seller_id: "5aa1c2c35ef7a4e97b5e995a",
        }},
              { "$count": "sales" },
            ],
             "02:00": [
              { "$match" : {createdAt: {$gte: ISODate("2020-05-10T02:00:00.000Z"),$lt: ISODate("2020-05-10T02:59:00.001Z")},seller_id: "5aa1c2c35ef7a4e97b5e995a",
        }},
              { "$count": "sales" },
            ],
             "03:00": [
              { "$match" : {createdAt: {$gte: ISODate("2020-05-10T03:00:00.000Z"),$lt: ISODate("2020-05-10T03:59:00.001Z")},seller_id: "5aa1c2c35ef7a4e97b5e995a",
        }},
              { "$count": "sales" },
            ],
          }},
          { "$project": {
            "ventas0": { "$arrayElemAt": [":00.sales", 0] },
            "ventas1": { "$arrayElemAt": [":00.sales", 0] },
            "ventas3": { "$arrayElemAt": [":00.sales", 0] },
          }}
        ])

但我确信有更有效的方法来做到这一点。

我的预期输出如下所示:

[countsale(00:00),countsale(01:00),countsale(02:00),countsale(03:00), etc to 24 hs]

你是对的,有更有效的方法来做到这一点。我们可以使用 Date expression operators and specifically by grouping with $hour.

db.getCollection('sales').aggregate([
    {
        $match: {
            createdAt: {$gte: ISODate("2020-05-10T00:00:00.000Z"), $lt: ISODate("2020-05-11T00:00:00.001Z")}
        }
    },
    {
        $group: {
            _id: {$hour: "$createdAt"},
            count: {$sum: 1}
        }
    },
    {
       $sort: {
          _id: 1
       }
    }
]);

这会给你这样的结果:

[
    {
        _id: 0,
        count: x
    },
    {
        _id: 1,
        count: y
    },
    ...
    {
        _id: 23,
        count: z
    }
]

从这里您可以根据需要轻松地重组数据。

我预见会发生的一个问题是没有任何匹配项的时间(即 count=0)将不存在于结果集中。您必须手动填补这些空白。