简体   繁体   中英

MongoDB aggregate merge two different fields as one and get count

I have following data in MongoDB:

[{id:3132, home:'NSH', away:'BOS'}, {id:3112, home:'ANA', away:'CGY'}, {id:3232, home:'MIN', away:'NSH'}]

Is it possible to get total game count for each team with aggregate pipeline?

desired result:

[{team: 'NSH', totalGames: 2}, {team:'MIN', totalGames: 1}, ...}]

i can get each on seperately to their own arrays with two aggregate calls:

[{$group: {_id: "$home", gamesLeft: {$sum: 1}}}]

and

[{$group: {_id: "$away", gamesLeft: {$sum: 1}}}]

resulting

var homeGames = [ { _id: 'NSH', totalGames: 1 }, { _id: 'SJS', totalGames: 2 }, ...]
var awayGames = [ { _id: 'NSH', totalGames: 1 }, { _id: 'SJS', totalGames: 4 }, ...]

But i really want to get it working with just one query. If not possible what would be the best way to combine these two results in to one using javascript?

After some puzzling, I found a way to get it done using an aggregate pipeline. Here is the result:

db.games.aggregate([{
        $project: {
            isHome: { $literal: [true, false] },
            home: true,
            away: true
        }
    }, {
        $unwind: '$isHome'
    }, {
        $group: {
            _id: { $cond: { if: '$isHome', then: '$home', else: '$away' } },
            totalGames: { $sum: 1 }
        }
    }
]);

As you can see it consists of three stages. The first two are meant to duplicate each document into one for the home team and one for the away team. To do this, the project stage first creates a new isHome field on each document containing a true and a false value, which the unwind stage then splits into separate documents containing either the true or the false value.

Then in the group phase, we let the isHome field decide whether to group on the home or the away field.

It would be nicer if we could create a team field in the project step, containing the array [$home, $away] , but mongo only supports adding array literals here, hence the workaround.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM