获取聚合中嵌套数组的总和 [英] Get sum of Nested Array in Aggregate
问题描述
好的,我有一个似乎无法解决的问题.
Ok, I have an issue I cannot seem to solve.
我有一个这样的文件:
{
"playerId": "43345jhiuy3498jh4358yu345j",
"leaderboardId": "5b165ca15399c020e3f17a75",
"data": {
"type": "EclecticData",
"holeScores": [
{
"type": "RoundHoleData",
"xtraStrokes": 0,
"strokes": 3,
},
{
"type": "RoundHoleData",
"xtraStrokes": 1,
"strokes": 5,
},
{
"type": "RoundHoleData",
"xtraStrokes": 0,
"strokes": 4
}
]
}
}
现在,我要完成的工作是使用笔画的总和,然后再对其进行排序.我正在尝试:
Now, what I am trying to accomplish is using aggregate sum the strokes and then order it afterwards. I am trying this:
var sortedBoard = db.collection.aggregate(
{$match: {"leaderboardId": boardId}},
{$group: {
_id: "$playerId",
played: { $sum: 1 },
strokes: {$sum: '$data.holeScores.strokes'}
}
},
{$project:{
type: "$SortBoard",
avgPoints: '$played',
sumPoints: "$strokes",
played : '$played'
}}
);
这里的问题是我确实获得了正确的笔画总和,因为它在另一个数组中.
The issue here is that I do net get the strokes sum correct, since this is inside another array.
希望有人可以帮助我,在此先感谢:-)
Hope someone can help me with this and thanks in advance :-)
推荐答案
您需要说
原因是因为您同时使用它两者作为求和数组值"的方式,也用作 The reason is because you are using it both as a way to "sum array values" and also as an "accumulator" for 您似乎遗漏的另一件事是 The other thing you appear to be missing is that 还请注意,您确实应该将聚合管道包装为官方数组 Also note you really should wrap aggregation pipelines as an official array 返回正确的课程详细信息: Returns the correct details of course: 这篇关于获取聚合中嵌套数组的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!$group
.$group
.$group
仅输出您告诉它的字段,因此,如果要访问其他阶段的其他字段或输出,则需要使用$group
only outputs the fields you tell it to, therefore if you want to access other fields in other stages or output, you need to keep them with something like $first
or another accumulator. We also appear to be missing a pipeline stage in the question anyway, but it's worth noting just to be sure.[]
,因为不赞成使用旧版用法,并且在某些语言实现中可能会引起问题.[]
, because the legacy usage is deprecated and can cause problems in some language implementations.{
"_id" : "43345jhiuy3498jh4358yu345j",
"avgPoints" : 1,
"sumPoints" : 12,
"played" : 1
}