我使用的是Mongodb 3.2,我需要计算数组中的所有字段
这是我收藏的一个例子
{
"memTotal" : 33730525659,
"swapTotal" : 16936129790,
"queueList" : [
{
"usedSlots" : 2,
"totalSlots" : 8,
"reservedSlots" : 0,
},
{
"usedSlots" : 2,
"totalSlots" : 8,
"reservedSlots" : 0,
},
{
"usedSlots" : 2,
"totalSlots" : 8,
"reservedSlots" : 0,
},
],
},
{
"memTotal" : 33730525659,
"swapTotal" : 16936129790,
"queueList" : [
{
"usedSlots" : 2,
"totalSlots" : 8,
"reservedSlots" : 0,
},
{
"usedSlots" : 2,
"totalSlots" : 8,
"reservedSlots" : 0,
},
{
"usedSlots" : 2,
"totalSlots" : 8,
"reservedSlots" : 0,
},
],
},
{
"memTotal" : 33730525659,
"swapTotal" : 16936129790,
"queueList" : [
{
"usedSlots" : 2,
"totalSlots" : 8,
"reservedSlots" : 0,
},
{
"usedSlots" : 2,
"totalSlots" : 8,
"reservedSlots" : 0,
},
{
"usedSlots" : 2,
"totalSlots" : 8,
"reservedSlots" : 0,
},
],
},
我需要计算" queueList.useSlots"," queueList.totalSlots"," queueList.totalSlots"的平均值,请记住queueList是一个阵列。
到目前为止,我所做的是使用聚合,首先是我{$ unwind:" queueList"},{$ group:{useSlots:{$ avg:" queueList.useSlots" }}
但这会返回错误的平均值: - (
任何帮助将非常感谢:-)谢谢!
答案 0 :(得分:2)
请尝试以下查询。
db.memory.aggregate([
{$unwind : "$queueList"},
{$group : {_id : "$_id",
"avgUseSlots" :{$avg : "$queueList.usedSlots"},
"avgTotSlots" :{$avg : "$queueList.totalSlots"},
"avgReservedSlots" :{$avg : "$queueList.reservedSlots"}
}
}
]);
<强>输出: - 强>
{
"_id" : ObjectId("57816e7285ae6441865d83e4"),
"avgUseSlots" : 2,
"avgTotSlots" : 8,
"avgReservedSlots" : 0
}