Mongodb并行Groupby

时间:2017-05-07 11:37:18

标签: mongodb mongodb-query aggregation-framework

我正在尝试聚合这个集合,我需要找不到特定团队的胜负

 {
 "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 }
                }
            }
            ])

是否可以在单个查询中获得胜负?

1 个答案:

答案 0 :(得分:1)

您可以使用[]括号将字段映射为数组,然后是$unwind& $group上的team$cond $sum winsloses。{/ 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]
            }
        }
    }
})