Q: Grabbing the max value from my MongoDB collection I need to return the player_id with the most total ipouts from my data structure. Here's what I need to do in pseudocode:
1. Add together all ipouts for each player
2. Grab the max ipouts
3. Display the player_id of the one with max ipouts

So far I have number one correct. This correctly lists each player ID and their total number of ipouts.
db.pitching.aggregate([ 
    { $group: 
        { _id: "$player_id", ipouts: 
            { $sum: "$ipouts" }
        }
     }
]);

Now the next step is to get the max. This is where I'm struggling:
db.pitching.aggregate([ 
    { $group: 
        { _id: "$player_id", ipouts: 
            { $sum: "$ipouts" }
        }
    },
    { $group: 
        { _id: "$_id" , max: { $max: "$ipouts"} }
    }
]);

Some other questions I've checked out don't work, as I know I need to use aggregate which means I cannot do a sort/limit(1). I've also tried setting the _id to null, which didn't work either. This code is returning an empty array (if i add toArray() I can see the empty brackets). 
How can I get the PlayerID of the object with the maximum ipouts?

A: Aggregate has its own version of sort and limit via the $sort and $limit pipeline operators. So you can do this as:
db.pitching.aggregate([ 
    { $group: 
        { _id: "$player_id", ipouts: 
            { $sum: "$ipouts" }
        }
    },
    { $sort: {ipouts: -1 } },
    { $limit: 1 }
]);

