[英]Mongoose/MongoDB sum up fields of an array for subdocuments
我对MongoDB / Mongoose相当陌生,我不知道应该如何获得想要的结果。 基本上我有一个像这样的文件:
{
"playerId" : "",
"sessions" : [
{
"start" : "",
"end" : "",
"join" : "",
"leave" : "",
"rounds" : [,
{
"name" : "roundName",
"weapons" : [
{
"name" : "weaponName",
"kills" : 1,
"assits" : 1,
"deaths" : 1,
"shots" : 1,
"headshots" : 1
},
{
"name" : "weaponName",
"kills" : 1,
"assits" : 1,
"deaths" : 1,
"shots" : 1,
"headshots" : 1
}
]
},
{
"name" : "roundName",
"weapons" : [
{
"name" : "weaponName",
"kills" : 1,
"assits" : 1,
"deaths" : 1,
"shots" : 1,
"headshots" : 1
},
{
"name" : "weaponName",
"kills" : 1,
"assits" : 1,
"deaths" : 1,
"shots" : 1,
"headshots" : 1
}
]
},
{
"name" : "roundName",
"weapons" : [
{
"name" : "weaponName",
"kills" : 1,
"assits" : 1,
"deaths" : 1,
"shots" : 1,
"headshots" : 1
},
{
"name" : "weaponName",
"kills" : 1,
"assits" : 1,
"deaths" : 1,
"shots" : 1,
"headshots" : 1
}
]
}
]
}
]
}
我想要的是一个查询,该查询在每个回合中添加了包含所有武器总和的字段(杀伤,死亡,助攻,爆头,射门)。 如果可能的话,整个会话也应如此。 任何帮助将不胜感激!
以下应该给您按会话->回合分组的统计信息列表:这里的假设是1)集合的名称是ShootingGame 2)字段的名称是$ sessions.Rounds.Weapons
db.shootingGame.aggregate(
[
{$group: {
_id: "$sessions.Rounds",
"sumkills": {$sum: "$sessions.Rounds.Weapons.kills" },
"sumasists": {$sum: "$sessions.Rounds.Weapons.assists" },
"sumdeaths": {$sum: "$sessions.Rounds.Weapons.deaths" },
"sumheadshots": {$sum: "$sessions.Rounds.Weapons.headshots" },
"sumshots": {$sum: "$sessions.Rounds.Weapons.shots" }
}}
]
)
但是,为了将每个会话进一步分组,您必须将此结果存储到另一个文档中,并每轮运行另一个$ sum组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.