使用mongodb聚合,有没有办法让查询在所有Scale上返回Weight average,平均为Scale 1,Scale 2的平均值全部在同一个查询中返回?
这是我的数据集中的条目示例
{
"Profile" : "P1",
"AvgWeight" : 639,
"Time" : "2017-04-14T05:17:42.000Z",
"Scale" : 1,
"Weight" : 1504,
"Target" : 680
}
我目前正在运行的查询是平均重量累积所有比例(可能没有帮助,但最好有更多信息)
[{
"$match": {
"Time": {
"$gt": moment(start).format("YYYY-MM-DD HH:mm:ss"),
"$lt": moment(end).format("YYYY-MM-DD HH:mm:ss")
}
}
},
{
"$group": {
"_id": {
"hour": {
"$hour": "$Time"
},
"day": {
"$dayOfYear": "$Time"
},
"interval": {
"$add": [{
"$multiply": [{
"$minute": "$Time"
}]
},
{
"$multiply": [{
"$hour": "$Time"
},
100
]
},
{
"$multiply": [{
"$dayOfYear": "$Time"
},
10000
]
},
{
"$multiply": [{
"$year": "$Time"
},
10000000
]
}
]
}
},
"time": {
"$first": "$Time"
},
"avgW": {
"$avg": "$AvgWeight"
},
"avgWe": {
"$avg": "$Weight"
},
"avgTarget": {
"$avg": "$Target"
}
}
}, {
"$sort": {
"Time": -1
}
}
]
添加预期的响应,例如
[
{
"_id : {"hour":1,"day":105,"interval":20971050122},
"time":"2017-04-15T01:22:58.000Z",
"avgW":646,
"avgWe":1577,
"avgTarget":680 ,
"Scale1" : 100 ,
"Scale2" : 120
} ,
{ "_id":{"hour":1,"day":105,"interval":20771050122},
"time":"2017-04-15T01:22:55.000Z",
"avgW":646,
"avgWe":1335,
"avgTarget":680 ,
"Scale1" : 100 ,
"Scale2" : 120 }
]
但是如果它有点不同我可以处理它,只要所有的比例都在同一个父对象中(这将是cpu密集的后期处理它们以链接匹配的组)
答案 0 :(得分:1)
您可以将第一组拆分为两组。
第一组计算所有体重的平均重量,第二组计算剩余的平均值。
类似的东西:
[{
"$match": {
"Time": {
"$gt": moment(start).format("YYYY-MM-DD HH:mm:ss"),
"$lt": moment(end).format("YYYY-MM-DD HH:mm:ss")
}
}
}, {
"$group": {
"_id": {
"scale": "$Scale",
"hour": {
"$hour": "$Time"
},
"day": {
"$dayOfYear": "$Time"
},
"interval": {
"$add": [{
"$multiply": [{
"$minute": "$Time"
}]
},
{
"$multiply": [{
"$hour": "$Time"
},
100
]
},
{
"$multiply": [{
"$dayOfYear": "$Time"
},
10000
]
},
{
"$multiply": [{
"$year": "$Time"
},
10000000
]
}
]
}
},
"time": {
"$first": "$Time"
},
"scaleAvg: {
"$avg": "$Weight"
}
}
}, {
"$group": {
"_id": {
"hour": "$_id.hour",
"day": "$_id.day",
"interval": "$_id.interval"
},
"time": {
"$first": "$time"
},
"avgW": {
"$avg": "$AvgWeight"
},
"avgWe": {
"$avg": "$Weight"
},
"avgTarget": {
"$avg": "$Target"
},
"scaleAvgs": {
"$push": {
"scale": "$_id.scale",
"scaleAvg": "$scaleAvg"
}
}
}
}, {
"$sort": {
"time": -1
}
}]