获取MongoDB的时间间隔数据

时间:2016-12-30 15:46:45

标签: mongodb mongodb-query aggregation-framework

我在Javascript中使用此代码以15分钟的间隔从我的MongoDB获取数据并以JSON格式存储。我没有收到任何错误,但我确定我做错了。:

test.js

var datetime = new Date();
var y = new Date();
datetime.setHours(datetime.getHours() - 168);
y.setMinutes(15);

 // construct aggregation pipeline retrieving last 15 minutes
var pipeline =  [
    {
        $group: {
            _id: {
                Time: "$datetime",
                Humidity: { $avg: "$humidity" }
            },
        },
    },
    { 
        $project : { 
            _id : 0, 
            "Time": {
                $range: [0, "$datetime", y]
            }, 
            Humidity: 1 
        } 
    },
    { $sort: { "_id.Time": -1, "Humidity": -1 } }
];

我将不胜感激。

这些是我的收藏中的项目

[{ "_id" : ObjectId("585db63541472bf7683eb3c5"), "datetime" : ISODate("2016-12-23T23:41:41.897Z"), "temperature" : 19, "humidity" : 23 }
{ "_id" : ObjectId("585db63a41472bf7683eb3c6"), "datetime" : ISODate("2016-12-23T23:41:46.927Z"), "temperature" : 19, "humidity" : 23 }
{ "_id" : ObjectId("585db63f41472bf7683eb3c7"), "datetime" : ISODate("2016-12-23T23:41:51.956Z"), "temperature" : 19, "humidity" : 23 }
{ "_id" : ObjectId("585db644483ab4f778a635bf"), "datetime" : ISODate("2016-12-23T23:41:56.991Z"), "temperature" : 19, "humidity" : 23 }
{ "_id" : ObjectId("585db64a483ab4f778a635c0"), "datetime" : ISODate("2016-12-23T23:42:02.032Z"), "temperature" : 19, "humidity" : 23 }]

我想获得一个JSON数据,输出平均湿度,在1小时内以特定的开始时间和结束时间间隔15分钟。

[{ "_id" : ObjectId("585db63541472bf7683eb3c5"),
 "datetime" : ISODate("2016-12-23T23:41:41.897Z"), // start time 
"humidity" : 23 }

{ "_id" : ObjectId("585db63a41472bf7683eb3c6"), 
"datetime" : ISODate("2016-12-23T23:56:46.927Z"),  
"humidity" : 23 }

{ "_id" : ObjectId("585db63f41472bf7683eb3c7"), 
"datetime" : ISODate("2016-12-23T23:11:51.956Z"),  
"humidity" : 23 }

{ "_id" : ObjectId("585db644483ab4f778a635bf"), 
"datetime" : ISODate("2016-12-23T23:26:56.991Z"),  //end time
"humidity" : 23 }]

I found my answer here

0 个答案:

没有答案