MongoDB中存储了一个时间序列数据,这里是每分钟存储的文档:
{ "_id" : ObjectId("54b7f78b33f0f76f26e49d79"), "timestamp" : ISODate("2015-01-15T17:23:23.215Z"),
"sensors_data" : {
"sen1" : { "@name" : "sensor-1", "@id" : "sen1", "value" : 10 },
"sen2" : { "@name" : "sensor-2", "@id" : "sen2", "value" : 27 },
"sen3" : { "@name" : "sensor-3", "@id" : "sen3", "value" : 19 },
"sen4" : { "@name" : "sensor-4", "@id" : "sen4", "value" : 25 },
}
}
我需要一个查询来计算每个子文档(sen1,sen2等)的值字段的平均值,结果如下:
{ "averages": { "sen1": "11.5", "sen2": "26", "sen3": "19.2", "sen4": "26.5" } }
答案 0 :(得分:1)
聚合框架用于获得所需的输出。
db.test.aggregate(
{
$group:
{
_id: null,
sen1: { $avg: "$sensors_data.sen1.value" },
sen2: { $avg: "$sensors_data.sen2.value" },
sen3: { $avg: "$sensors_data.sen3.value" },
sen4: { $avg: "$sensors_data.sen4.value" }
}
}
)
OUTPUT(样本数据):
{
"result" : [
{
"_id" : null,
"sen1" : 11,
"sen2" : 28.5,
"sen3" : 24,
"sen4" : 38.5
}
],
"ok" : 1
}