以下是我的示例数据:
{
"_id": {
"$oid": "5654a8f0d487dd1434571a6e"
},
"ValidationDate": {
"$date": "2015-11-24T13:06:19.363Z"
},
"DataRaw": " WL 00100100012015-08-28 02:44:17+0000+ 16.81 8.879 1084.00",
"ReadingsAreValid": true,
"locationID": " WL 001",
"Readings": {
"pH": {
"value": 8.879
},
"SensoreDate": {
"value": {
"$date": "2015-08-28T02:44:17.000Z"
}
},
"temperature": {
"value": 16.81
},
"Conductivity": {
"value": 1084
}
},
"HMAC":"ecb98d73fcb34ce2c5bbcc9c1265c8ca939f639d791a1de0f6275e2d0d71a801"
}
我尝试将平均值分组两个小时,并进行以下聚合查询。
Query = [{"$unwind":"$Readings"},
{'$group' : { "_id": {
"year": { "$year": "$Readings.SensoreDate.value" },
"dayOfYear": { "$dayOfYear": "$Readings.SensoreDate.value" },
"interval": {
"$subtract": [
{ "$hour": "$Readings.SensoreDate.value"},
{ "$mod": [{ "$hour": "$Readings.SensoreDate.value"},2]}
]
}
}},
'AverageTemp' : { '$avg' : '$Readings.temperature.value'}, "AveragePH": {"$avg" : "$Readings.pH.value"}, "AverageConduc": {"$avg" : "$Readings.Conductivity.value"}}
, {"$limit":10}]
这给我一个错误的说法
A pipeline stage specification object must contain exactly one field.
我完成了所有研究,但无法获得理想的结果。
答案 0 :(得分:1)
经过一些格式化后,您现在的聚合管道如下所示:
Query = [
{ "$unwind": "$Readings" },
{
'$group' : {
"_id": {
"year": { "$year": "$Readings.SensoreDate.value" },
"dayOfYear": { "$dayOfYear": "$Readings.SensoreDate.value" },
"interval": {
"$subtract": [
{ "$hour": "$Readings.SensoreDate.value"},
{
"$mod": [
{ "$hour": "$Readings.SensoreDate.value" },
2
]
}
]
}
}
},
'AverageTemp' : { '$avg' : '$Readings.temperature.value' },
"AveragePH": { "$avg" : "$Readings.pH.value" },
"AverageConduc": { "$avg" : "$Readings.Conductivity.value" }
},
{ "$limit": 10 }
]
mongo正在抱怨
管道阶段规范对象必须只包含一个字段。
因为它无法识别错位的字段
'AverageTemp' : { '$avg' : '$Readings.temperature.value' },
"AveragePH": { "$avg" : "$Readings.pH.value" },
"AverageConduc": { "$avg" : "$Readings.Conductivity.value" }
正确的管道应该在 $group
管道阶段中包含这些字段,因此有一个工作管道:
Query = [
{ "$unwind": "$Readings" },
{
"$group" : {
"_id": {
"year": { "$year": "$Readings.SensoreDate.value" },
"dayOfYear": { "$dayOfYear": "$Readings.SensoreDate.value" },
"interval": {
"$subtract": [
{ "$hour": "$Readings.SensoreDate.value"},
{
"$mod": [
{ "$hour": "$Readings.SensoreDate.value" },
2
]
}
]
}
},
"AverageTemp" : { "$avg" : "$Readings.temperature.value" },
"AveragePH": { "$avg" : "$Readings.pH.value" },
"AverageConduc": { "$avg" : "$Readings.Conductivity.value" }
}
},
{ "$limit": 10 }
]