You can use Aggregation.
const lowerRange = { $lt: ["$person_age", 20] };
const middleRange = { $and: [{ $gte: ["$person_age", 20]}, { $lte: ["$person_age", 40] }] };
// const upperRange = { $gt: ["$person_age", 40] };
db.range.aggregate([
{
$project: {
ageRange: {
$cond: {
if: lowerRange,
then: "lowerRange",
else: {
$cond: {
if: middleRange,
then: "middleRange",
else: "upperRange"
}
}
}
}
}
},
{
$group: {
_id: "$ageRange",
count: { $sum: 1 }
}
}
]);
Here the total count is not included as you can calculate it from the count of the ranges. If you have more that 3 ranges, a better idea would be to pass an array of $cond statements to the project stage, as nesting multiple if/else statements starts to get harder to maintain. Here is a sample:
$project: {
"ageRange": {
$concat: [
{ $cond: [ { $lt: ["$person_age", 20] }, "0-19", ""] },
{ $cond: [ { $and: [ { $gte: ["$person_age", 20] }, { $lte: ["$person_age", 40] } ] }, "20-40", ""] },
{ $cond: [ { $gt: ["$person_age", 40] }, "41+", ""] }
]
}
}