Arrays 仅查询嵌套数组中的数字
我试图获取文档中嵌套数组中键的平均数,但不确定如何实现这一点 以下是我的文档的外观:Arrays 仅查询嵌套数组中的数字,arrays,mongodb,aggregation-framework,average,Arrays,Mongodb,Aggregation Framework,Average,我试图获取文档中嵌套数组中键的平均数,但不确定如何实现这一点 以下是我的文档的外观: { "_id": { "$oid": "XXXXXXXXXXXXXXXXX" }, "data": { "type": "PlayerRoundData", "playerId": "XXXXXXXXXXXXX", "groupId": "XXXXXXXXXXXXXX", "holeScores": [ { "type": "Rou
{
"_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
}
]
}
}
现在,棘手的部分是,我只想要所有具有此playerid和此groupid的文档的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" }
}}
);
真的希望在此问题上获得帮助,并提前感谢:-)您可以在下面尝试
db.collection.aggregate(
{ "$match": { "data.groupId": groupId, "data.playerId": playerId }},
{ "$group": {
"_id": null,
"result": {
"$sum": {
"$arrayElemAt": [
"$data.holeScores.points",
0
]
}
}
}}
)
您可以使用withincludearayindex
获取索引,然后使用$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" }
}
}
)
它会出现以下错误:函数聚合不接受参数(对象)。?有什么想法吗?它出现了这个错误:函数聚合不接受参数(对象)。?有什么好主意吗?太好了,它很管用。不过我有一个问题。在平均值数组出现之前,是否也可以在输出中获得playerid?@Mansa当然,修改了我的答案