Użyj $addToSet
akumulator, a następnie $size
operator do zliczania unikalnych projectId
Worksheet.aggregate([
{ $match: conditions },
{ "$group": {
"_id": null,
"billingHours": {
"$sum": {
"$cond": [{ "$eq": ["$isBilling", true] }, "$hours", 0]
}
},
"fixContract": {
"$sum": {
"$cond": [{ "$eq": ["$isBilling", true] }, 0, "$hours"]
}
},
"projectIds": { "$addToSet": "$projectId" }
}},
{ "$addFields": { "projectIds": { "$size": "$projectIds" }}}
])