I have grouped some data by some conditions and get the expected result. However, I would like to only return the item with the highest number in each pool
. If I only would like to have the highest one I could add .sort({ correctBets: -1 }).limit(1)
to the end, but now I need one in each pool. And if two or more correctBets is the same in one pool I would like to return all those items. How would I do this?
const coupon = await CouponModel.aggregate([
{
$match: {
eventId: { $in: eventIds },
},
},
{
$group: {
_id: {
userId: '$userId',
pool: '$pool',
},
correctBets: {
$sum: '$correctBets',
},
},
},
])
This is the data I get returned from the aggregate.
[
{ _id: { userId: '5df344a1372f345308dac12a', pool: 'foo' },
correctBets: 9 },
{ _id: { userId: '5dfb2db245011a390fec4f7d', pool: 'bar' },
correctBets: 6 },
{ _id: { userId: '5df344a1372f345308dac12a', pool: 'bar' },
correctBets: 5 },
{ _id: { userId: '5dfb2db245011a390fec4f7d', pool: 'foo' },
correctBets: 11 }
]
My expected result should look like this
[
{ _id: { userId: '5dfb2db245011a390fec4f7d', pool: 'foo' },
correctBets: 11 },
{ _id: { userId: '5dfb2db245011a390fec4f7d', pool: 'bar' },
correctBets: 6 }
]
Edit: the proposed duplicate question dont handle max values for each 'key' as in my case is two pools. Foo and bar.