我在该收藏字段中收藏了状态。状态采用 arrayIndex 格式。采集样本如下 在计算完我想要的结果后,我必须计算平均值 0、1 和 2,如下所示
{
"result": [
{
"0": 18,
"1": 58,
"2": 24
}
]
}
是否可以得到以上格式的结果?如果是,请建议我如何计算平均值?
最佳答案
用于运行聚合操作以获取给定数组中第一、第二和第三状态的平均值的 mongodb shell 查询如下:
var pipeline = [
{
"$match": {
"Status.0": { $exists: true },
"Status.1": { $exists: true },
"Status.2": { $exists: true }
}
},
{ "$unwind": "$Status" },
{
"$match": {
"Status.0": { $exists: true },
"Status.1": { $exists: true },
"Status.2": { $exists: true }
}
},
{
"$group": {
"_id": null,
"0": { "$avg": "$Status.0" },
"1": { "$avg": "$Status.1" },
"2": { "$avg": "$Status.2" }
}
}
]
db.status.aggregate(pipeline);
关于php - 如何使用 MongoDB 计算单个字段的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38010618/