WorkaroundNewbie
WorkaroundNewbie

Reputation: 1141

Mongodb parallel Groupby

I am trying to aggregate this collection where I need to find no of wins and loss of a particular team

 {
 "team1" :"ruby",
 "team2" :"jade",
"winner" :"ruby"
},
{
 "team1" :"jade",
 "team2" :"ruby",
 "winner" :"jade"
}

to

{
 "team" :"ruby",
 "wins" :1, 
 "loss" :1
},
{
 "team" :"jade",
 "wins" :1, 
 "loss" :1
}

only thing I could think of is three queries of group by like this and combain them both by same name

aggregate(
            [{
                $group: {
                    _id: "$winner",
                    wins: { $sum: 1 }
                }
            }
            ])

is it possible to obtain wins and losses in single query

Upvotes: 0

Views: 390

Answers (1)

s7vr
s7vr

Reputation: 75934

You can use [] brackets to map fields as arrays followed by $unwind & $group on team and $cond with $sum to count wins and loses.

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

Upvotes: 1

Related Questions