0

我是 Mongo 聚合的新手,我正试图让以下工作。

我有以下文件:

{
  "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
}
...
}

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

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

这是我目前无法使用的代码(15 分钟时间片):

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);

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

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

database.aggregate(
"{ $match: { '_id': " + gatewayId + " }}")  

.and("{ $facet: 
    { 'Averages': [
        { $unwind: '$gatewayReadings' },
        { $sort: {'gatewayReadings.timestamp': 1}},
        { $group: { _id: {
            year: { $year: '$gatewayReadings.timestamp' },
            dayOfYear: { $dayOfYear: '$gatewayReadings.timestamp' },
            interval: { $subtract: [ 
                { $minute: '$gatewayReadings.timestamp' },
                { $mod: [{ $minute: '$gatewayReadings.timestamp'}, 15] }
            ]}},
            timestamp: { $last: '$gatewayReadings.timestamp'},
            temperature_1: { $avg: '$gatewayReadings.temperature_1'},
            temperature_2: { $avg: '$gatewayReadings.temperature_2'}, 
            battery_voltage: { $avg: '$gatewayReadings.battery_voltage'},
            count: { $sum: 1} } 
        }]
    }
}").as(Object.class)
4

0 回答 0