Q:

MongoDB - How to extract field with max value

I have a MongoDb collection genre_count as 
user | genre         | count
-----+---------------+-------
1    | Western       | 2
1    | Adventure     | 1
1    | Comedy        | 5
2    | Western       | 3
2    | Thriller      | 1
2    | Romance       | 2

I need to extract the genre for each user with maximum count i.e. for user 1 , the genre with maximum count is Comedy with Count 5. I tried using couple of ways as: 
db.genre_count.aggregate([
  {
  $group:{
     _id:{

        user:"$user",
        genre:"$genre"
     },
     max_val:{
         $max: "$count"
     }
   }
 }
])

I thought this would work but it returned the count of the user for each genre so basically it returned me all the records.
Then I tried another solution which worked partially in :
db.genre_count.aggregate([
  {
  $group:{
     _id:{

        user:"$user"
     },
     max_val:{
         $max: "$count"
     }
   }
 }
])

But this only returned the maximum value as it has no corresponding genre information for that maximum value. Is there any way I can get the desired result?

A:

To return the maximum count and genre list, you need to use the $max in your group stage to return the maximum "Count" for each group then use $push accumulator operator to return a list of "Genre Name" and "Count" for each group. 
From there you need to use the $map operator in your $project stage to return a list of genre_names alongside the maximum count. The $cond here is used to compare each genre count to the maximum value.
db.genre_count.aggregate([
        { '$group': {
            '_id': '$user', 
            'maxCount': { '$max': '$count' }, 
            'genres': { 
                '$push': {
                    'name': '$genre', 
                    'count': '$count' 
                }
            }
        }}, 
        { '$project': { 
            'maxCount': 1, 
            'genres': { 
                '$setDifference': [
                    { '$map': {
                        'input': '$genres', 
                        'as': 'genre', 
                        'in': {
                            '$cond': [
                                { '$eq': [ '$$genre.count', '$maxCount' ] }, 
                                '$$genre.name', 
                                false
                            ]
                        }
                    }}, 
                    [false]
                ]
            }
        }}
    ])

