我正在尝试聚合这个集合,我需要找不到特定团队的胜负
{
"team1" :"ruby",
"team2" :"jade",
"winner" :"ruby"
},
{
"team1" :"jade",
"team2" :"ruby",
"winner" :"jade"
}
到
{
"team" :"ruby",
"wins" :1,
"loss" :1
},
{
"team" :"jade",
"wins" :1,
"loss" :1
}
我能想到的只有三个像这样的群组查询,并且用同名来组合它们
aggregate(
[{
$group: {
_id: "$winner",
wins: { $sum: 1 }
}
}
])
是否可以在单个查询中获得胜负?
答案 0 :(得分:1)
您可以使用[]
括号将字段映射为数组,然后是$unwind
& $group
上的team
和$cond
$sum
wins
和loses
。{/ p>
db.collection.aggregate({
$project: {
winner: 1,
team: ["$team1", "$team2"]
}
}, {
$unwind: "$team"
}, {
$group: {
_id: "$team",
wins: {
$sum: {
$cond: [{
$eq: ["$winner", "$team"]
}, 1, 0]
}
},
loses: {
$sum: {
$cond: [{
$eq: ["$winner", "$team"]
}, 0, 1]
}
}
}
})