Hello!
I have a collection with about 100k documents (and this number increases every month), and I need to count the documents based on some filter parameters. I’m using aggregation with $group
, but in some cases, I need to perform complex checks within the $group
stage. I wanted to know if there might be a better way to achieve this:
const result = await collection.aggregate([
{
$match: {
product: params.product, // this is dynamic
resolved: { $ne: true },
},
},
{
$group: {
_id: null,
countItemsGeneratedWithDelay: {
$sum: {
$cond: [
{
$and: [
{ $eq: [generated, true] },
{ $eq: [shouldGenerate, true] },
{ $eq: [hasDelayOnGeneration, true] },
],
},
1,
0,
],
},
},
countNotGeneratedItems: {
$sum: {
$cond: [
{
$and: [
{ $eq: [generated, false] },
{ $eq: [shouldGenerate, true] },
],
},
1,
0,
],
},
},
countItemsWithAlertLevelLow: {
$sum: { $cond: [{ $eq: [alertLevel, 'low'] }, 1, 0] },
},
countItemsWithAlertLevelMedium: {
$sum: { $cond: [{ $eq: [alertLevel, 'medium'] }, 1, 0] },
},
countItemsWithAlertLevelHigh: {
$sum: { $cond: [{ $eq: [alertLevel, 'high'] }, 1, 0] },
},
},
},
{
$project: {
_id: 0,
alertLevel: {
low: '$countItemsWithAlertLevelLow',
medium: '$countItemsWithAlertLevelMedium',
high: '$countItemsWithAlertLevelHigh',
},
countNotGeneratedItems: 1,
countItemsGeneratedWithDelay: 1,
},
},
]).toArray();
I have many more conditions to check and count. Is there a better way to achieve the same result?