mongodb聚合$匹配日期未给出预期结果

时间:2017-04-30 08:40:32

标签: mongodb aggregation-framework

我有这个聚合:

{   
    "$group": {
        "_id": "$key",
        "temp": {"$last": "$temp"},
        "name": {"$last": "$name"},
        "ts": {"$last": "$ts"},
        "maxTemp": {"$max": "$temp"},
        "minTemp": {"$min": "$temp"}
    }
}

给了我这个结果:

[
    {"_id":"bedroom","temp":21.875,"name":"Bedroom","ts":"2017-04-30T08:33:44.789Z","maxTemp":24.875,"minTemp":21.437},
    {"_id":"livingRoom","temp":18.812,"name":"Living Room","ts":"2017-04-30T08:24:40.126Z","maxTemp":19.625,"minTemp":17.625}
]

但我希望将此限制为过去24小时,因此我将其更改如下:

let now = new Date();
let yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
[
    {
        "$match": {
            "ts": {$gte: yesterday}
        }
    },
    {   
        "$group": {
            "_id": "$key",
            "temp": {"$last": "$temp"},
            "name": {"$last": "$name"},
            "ts": {"$last": "$ts"},
            "maxTemp": {"$max": "$temp"},
            "minTemp": {"$min": "$temp"}
        }
    }
]

我得到了这些结果:

[
    {"_id":"livingRoom","temp":18.75,"name":"Living Room","ts":"2017-04-30T08:06:41.000Z","maxTemp":19.625,"minTemp":17.625},
    {"_id":"bedroom","temp":21.875,"name":"Bedroom","ts":"2017-04-30T08:24:04.000Z","maxTemp":23.812,"minTemp":21.437}
]

最后一条记录的ts已经改变。匹配应该只影响最小值和最大值,而不是最后一个值的时间戳,但匹配似乎过滤掉了比过去记录更近的记录。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

似乎问题是日期的比较。按如下方式修改它:

let now = new Date();
let yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
[
    {
        "$match": {
            "ts": {$gte: yesterday.toISOString()}
        }
    },
    {   
        "$group": {
            "_id": "$key",
            "temp": {"$last": "$temp"},
            "name": {"$last": "$name"},
            "ts": {"$last": "$ts"},
            "maxTemp": {"$max": "$temp"},
            "minTemp": {"$min": "$temp"}
        }
    }
]