Mongoose根据时差汇总文档

时间:2015-11-26 15:49:56

标签: node.js mongodb aggregation-framework

我有一个包含以下字段的模式

var MySchema = new Schema({
  roomId: { type: String, required: true, ref: 'Room' },
  timestamp: Date,
  currentTemp: Number,
  outsideTemp: Number,
  desiredTemp: Number
});

现在我想聚合此集合中的文档并返回响应,如

{
    timestamp: [1,2,3,4,5,6,7,8,9,10..,24],
    currentTemp: [34,45,.....],
    outsideTemp: [14,45,.....],
    desiredTemp: [34,45,.....]
}

我有一些匹配条件,我可以根据匹配条件选择文档。现在我想聚合选定的文档并产生如上所示的结果。

时间戳值由下限和上限绑定。上限和下限从客户端传递,聚合应基于下限和上限之间的差异。如果差异是

- 1 day : group by hour

- 3 days : group by 6 hrs

- 7 days : group by 12 hours

- < 30 days : group by day

- > 30 days : group by week

currentTemp是该时间段内currentTemp属性的所有文档的平均值。类似于outsideTemp和desiredTemp。

我该怎么做?

编辑:

样本数据集

{
            "_id": "5656bfd94d6f6304ff140000",
            "roomId": "5656bc124d6f6335051b0000",
            "timestamp": "2015-11-15T08:59:20Z",
            "currentTemp": 10.55,
            "outsideTemp": 43.83,
            "desiredTemp": 21.32
        }, {
            "_id": "5656bfd94d6f6304ff150000",
            "roomId": "5656bc124d6f633505200000",
            "timestamp": "2015-06-01T06:33:49Z",
            "currentTemp": 32.47,
            "outsideTemp": 49.65,
            "desiredTemp": 20.99
        }, {
            "_id": "5656bfd94d6f6304ff160000",
            "roomId": "5656bc124d6f633505250000",
            "timestamp": "2014-12-31T23:47:54Z",
            "currentTemp": 35.69,
            "outsideTemp": 29.91,
            "desiredTemp": 20.15
        }, {
            "_id": "5656bfd94d6f6304ff170000",
            "roomId": "5656bc124d6f6335051e0000",
            "year": 2015,
            "month": 3,
            "day": 12,
            "hour": 21,
            "minute": 13,
            "second": 38,
            "inDST": true,
            "timestamp": "2015-11-14T07:56:42Z",
            "currentTemp": 27.65,
            "outsideTemp": 41.4,
            "desiredTemp": 24.68
        }

0 个答案:

没有答案