MongoDB根据时间戳聚合在数组中的平均值

时间:2017-02-09 10:44:08

标签: mongodb morphia jongo

我是Mongo聚合的新手,我正在努力让以下工作。

我有以下文件:

setattr(A, "array", "temp")

我试图根据1分钟,15分钟,1小时等的时间片获得每个gatewayReadings字段的平均值。

我使用morphia,但认为使用Jongo进行聚合会更容易。

以下是我目前拥有的代码(15分钟时间片段),我无法上班:

{
  "gatewayId" : 3,
  "gatewayReadings" : [ {
  "timestamp" : 1486570609479,
  "temperature_1" : 28.5625,
  "temperature_2" : 30.375,
  "battery_voltage" : 3.525
 }, {
  "timestamp" : 1486570624479,
  "temperature_1" : 29.75,
  "temperature_2" : 30.375,
  "battery_voltage" : 3.525
 }, {
  "timestamp" : 1486570639479,
  "temperature_1" : 33.0625,
  "temperature_2" : 32.0,
  "battery_voltage" : 3.525
}, {
  "timestamp" : 1486570669481,
  "temperature_1" : 30.375,
  "temperature_2" : 29.75,
  "battery_voltage" : 3.525
}
...
}

我做错了什么? 任何帮助将不胜感激(Jongo或morphia)。

更新: 我最终得到了这个:

Aggregate.ResultsIterator<Object> readings = 
            gatewayComputed.aggregate(
                "{ $match: { 'gatewayId': " + gatewayId + " }}," +
                "{ $unwind: '$gatewayReadings' }," +
                "{ $group: {"+ 
                    "_id:  { " + 
                        "$subtract: [" +
                        "{ $subtract: [ '$timestamp', new Date('1970-01-01') ] }," +
                        "{ $mod: [ " +
                            "{ $subtract: [ '$timestamp', new Date('1970-01-01') ] }," +
                            "1000 * 60 * 15" +
                            "]}" +                          
                        "]" +
                    "}," +                  //end of _id
                    "temperature_1 : { $avg : '$temperature_1' }," +
                    "temperature_2 : { $avg : '$temperature_2' }," +
                    "battery_voltage : { $avg : '$battery_voltage' }" +
                "}}"                        //end of group
            ).as(Object.class);

0 个答案:

没有答案