查询使用每个平均值的计数查找 mongodb 中存储的平均值的平均值
query for finding average of average stored in mongodb using count of every average
我们有这样的数据
{
"_id" : ObjectId("64326493749326499446"),
"dId" : "d_155",
"pId" : "5f4cb595cff47e0001b20882",
"sId" : "825",
"paramName" : "Utility_Air_Flow",
"avg" : 488270.454545455,
"count" : NumberLong(220),
"date" : ISODate("2020-09-03T18:30:00.000Z"),
"dataPerHour" : {
"19" : {
"min" : 8399.0,
"max" : 995990.0,
"avg" : 488270.454545455,
"count" : NumberLong(220),
"values" : [
{
"paramValue" : "90235",
"time" : ISODate("2020-09-04T13:37:07.000Z")
},
{
"paramValue" : "272297",
"time" : ISODate("2020-09-04T13:37:14.000Z")
}
]
},
"20" : {
"min" : 8399.0,
"max" : 995990.0,
"avg" : 488270.454545455,
"count" : NumberLong(220),
"values" : [
{
"paramValue" : "90235",
"time" : ISODate("2020-09-04T13:37:07.000Z")
},
{
"paramValue" : "272297",
"time" : ISODate("2020-09-04T13:37:14.000Z")
}
]
}
},
"_class" : "org.nec.iotplatform.entities.RawData"
}
我们需要找到 dataPerHour 中已存储的所有平均值的平均值。
我们需要根据公式求平均值:
(average1count1)+(avarege2count2)+
(average3*count3)/(count1+count2+count3)
您可以使用以下查询:
db.collection.aggregate([
{
$project: {
dataPerHour: {
$objectToArray: "$dataPerHour"
}
}
},
{
$project: {
"average": {
"$divide": [
{
$reduce: {
input: "$dataPerHour",
initialValue: 0,
in: {
"$add": [
"$$value",
{
"$multiply": [
"$$this.v.count",
"$$this.v.avg"
]
}
]
}
}
},
{
$reduce: {
input: "$dataPerHour",
initialValue: 0,
in: {
"$add": [
"$$value",
"$$this.v.count"
]
}
}
}
]
}
}
}
])
我们有这样的数据
{
"_id" : ObjectId("64326493749326499446"),
"dId" : "d_155",
"pId" : "5f4cb595cff47e0001b20882",
"sId" : "825",
"paramName" : "Utility_Air_Flow",
"avg" : 488270.454545455,
"count" : NumberLong(220),
"date" : ISODate("2020-09-03T18:30:00.000Z"),
"dataPerHour" : {
"19" : {
"min" : 8399.0,
"max" : 995990.0,
"avg" : 488270.454545455,
"count" : NumberLong(220),
"values" : [
{
"paramValue" : "90235",
"time" : ISODate("2020-09-04T13:37:07.000Z")
},
{
"paramValue" : "272297",
"time" : ISODate("2020-09-04T13:37:14.000Z")
}
]
},
"20" : {
"min" : 8399.0,
"max" : 995990.0,
"avg" : 488270.454545455,
"count" : NumberLong(220),
"values" : [
{
"paramValue" : "90235",
"time" : ISODate("2020-09-04T13:37:07.000Z")
},
{
"paramValue" : "272297",
"time" : ISODate("2020-09-04T13:37:14.000Z")
}
]
}
},
"_class" : "org.nec.iotplatform.entities.RawData"
}
我们需要找到 dataPerHour 中已存储的所有平均值的平均值。
我们需要根据公式求平均值:
(average1count1)+(avarege2count2)+ (average3*count3)/(count1+count2+count3)
您可以使用以下查询:
db.collection.aggregate([
{
$project: {
dataPerHour: {
$objectToArray: "$dataPerHour"
}
}
},
{
$project: {
"average": {
"$divide": [
{
$reduce: {
input: "$dataPerHour",
initialValue: 0,
in: {
"$add": [
"$$value",
{
"$multiply": [
"$$this.v.count",
"$$this.v.avg"
]
}
]
}
}
},
{
$reduce: {
input: "$dataPerHour",
initialValue: 0,
in: {
"$add": [
"$$value",
"$$this.v.count"
]
}
}
}
]
}
}
}
])