I have a collection with documents, like this:
{
_id: ObjectId('xyz'),
companyId: 'xyz',
lastModifiedByUserEmail: '[email protected]'
}
I need to know the lastModifiedByUserEmail with more occurrences, the quantity of occurrences, by companyId.
I know how to make the the count of occurrences by lastModifiedByUserEmail:
{ $group: { _id: '$lastModifiedByUserEmail', total: { $sum: 1 } } }
But I don't know how to group it by companyId.
CodePudding user response:
You can add a multi-part id to group on:
{
$group: {
_id: {
"lastModifiedByUserEmail": "$lastModifiedByUserEmail",
"company": "$companyId"
},
total: {
$sum: 1
}
}
}
If you want to get the highest, then add in a sort and limit?
{
$sort: {
total: -1
}
},
{
$limit: 1
}