MongoDB 按 UNIX 时间分组并计算无效

MongoDB group by UNIX time and count not working

我有一份文件,看起来像

{
    "_id" : ObjectId("57dffd3b65291f06dab34385"),
    "user" : "12345667890"
    "time" : NumberLong(1474297140186)
}

我正在尝试计算某个应用程序的访问者数量。我有 64 个字段,我的查询如下所示。

db.convo_log.aggregate([
   {
       '$group': {
            '_id': { 
                month: { $month: new Date("$time") }, 
                day: { $dayOfMonth: new Date("$time") }, 
                year: { $year: new Date("$time") } 
            }, 
            'count': { '$sum': 1 }
       }
   }
])

即使我正在寻找多个组(因为有来自不同日期的数据)它 returns 因为

{
    "_id" : {
        "month" : 8,
        "day" : 17,
        "year" : 292278994
    },
    "count" : 64.0
}

我这里有什么地方做错了吗?

您不能通过这种方式从时间戳创建日期对象表示。您需要使用 arithmetic operators i.e. $add 时间戳对 new Date(0) 对象构造函数进行一些算术运算,该构造函数将日期表示为距纪元 0 毫秒(尽管形式较短)。

总和 { "$add": ["$time", new Date(0)] } 产生一个新的日期对象。因此,将其与 $dateToString 运算符放在一起,您可以 运行 此管道获得所需的结果:

db.convo_log.aggregate([
    {
        "$project": {
            "formattedDate": {
                "$dateToString": {
                    "format": "%Y-%m-%d",
                    "date": { "$add": ["$time", new Date(0)] }
                }
            }
        }
    },
    {
        "$group": {
            "_id": "$formattedDate",
            "count": { "$sum": 1 }
        }
    }
])