我正在尝试获取文档内嵌套数组中键的平均数量,但不确定如何完成此操作。
这是我的文档的样子:
{
"_id": {
"$oid": "XXXXXXXXXXXXXXXXX"
},
"data": {
"type": "PlayerRoundData",
"playerId": "XXXXXXXXXXXXX",
"groupId": "XXXXXXXXXXXXXX",
"holeScores": [
{
"type": "RoundHoleData",
"points": 2
},
{
"type": "RoundHoleData",
"points": 13
},
{
"type": "RoundHoleData",
"points": 3
},
{
"type": "RoundHoleData",
"points": 1
},
{
"type": "RoundHoleData",
"points": 21
}
]
}
}
现在,棘手的部分是我只想要具有此玩家 ID 和此组 ID 的所有文档的holeScores [0] 的平均分。
实际上,最好的解决方案是收集带有playerid和groupid的所有文档,并创建一个具有holeScores [0],holeScores [1],holeScores [2]的平均值的新数组...但如果我只能得到一个当时的数组键,那就可以了:-)
这是我的想法,但不确定如何将它们组合在一起:
var allScores = dbCollection('scores').aggregate(
{$match: {"data.groupId": groupId, "playerId": playerId}},
{$group: {
_id: playerId,
rounds: { $sum: 1 }
result: { $sum: "$data.scoreTotals.points" }
}}
);
真的希望得到有关此问题的帮助,并提前致谢:-)
最佳答案
您可以使用$unwind使用 includeArrayIndex
获取索引,然后使用 $group
按该索引进行分组
dbCollection('scores').aggregate(
{
$match: { "data.playerId": "XXXXXXXXXXXXX", "data.groupId": "XXXXXXXXXXXXXX" }
},
{
$unwind: {
path: "$data.holeScores",
includeArrayIndex: "index"
}
},
{
$group: {
_id: "$index",
playerId: { $first: "data.playerId" },
avg: { $avg: "$data.holeScores.points" }
}
}
)
关于arrays - 仅查询嵌套数组中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52585090/