I\'m trying to figure out if there is a way to code a conditional unwind in MongoDB\'s aggregation framework.
I have an aggregation command like this:
mo
Build up your aggregation pipeline programmatically prior to calling 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) {
//...
});