geniuslinchao
geniuslinchao

Reputation: 72

How to select max item in each group?

The collection is like below:

Name      Subject    Score
Li        Math       89
Wang      Math       97
Su        Math       85
Li        History    80
Wang      History    73
Su        History    75
Li        Science    90
Wang      Science    83
Su        Science    65

I want to get the highest subject for everyone, result like:

Li        Science    90
Wang      Math       97
Su        Math       85

Upvotes: 2

Views: 811

Answers (1)

sambomartin
sambomartin

Reputation: 6813

Something like this should do the trick

db.scores.aggregate(  { $group: {
     _id: { name: "$name", subject: "$subject" },
     'maxscore': { $max : "$score" }
}})

Upvotes: 1

Related Questions