Programowo zbuduj potok agregacji przed wywołaniem aggregate
:
var pipeline = [];
pipeline.push(
{ // SELECT
$project : { "sex" : 1,
"salesIndex":1
}
},
{ // WHERE
$match: {"salesIndex": {$gte: index}}
}
);
if (filteringByDepartment) {
pipeline.push(
{ $unwind: '$departments' },
{ $match: { departments: departmentId }}
);
}
pipeline.push(
{ // GROUP BY y agregadores
$group: {
_id : "$sex",
sexCount : { $sum: 1 }
}
},
{ $sort: { sexCount: -1 } }
);
models.Users.aggregate(pipeline, function(err, dbres) {
//...
});