Можно попробовать запрос агрегации ниже:
db.collection.aggregate([
/** Group on 'nat' field & sum no.of doc's based on age to specific category using conditional check */
{
$group: {
_id: "$nat",
"0-30": {
$sum: {
$cond: [
{ $and: [{ $gte: ["$dob.age", 0] }, { $lt: ["$dob.age", 30] }] },
1,
0
]
}
},
"30-50": {
$sum: {
$cond: [
{ $and: [{ $gte: ["$dob.age", 30] }, { $lt: ["$dob.age", 50] }] },
1,
0
]
}
},
"50plus": { $sum: { $cond: [{ $gte: ["$dob.age", 50] }, 1, 0] } }
}
},
/** Group on nationality & push male & female objects into respective arrays */
{
$group: {
_id: "$_id.nationality",
male: {
$push: {
$cond: [
{ $eq: ["$_id.gender", "male"] },
{
"0-30": "$$ROOT.0-30",
"30-50": "$$ROOT.30-50",
"50plus": "$$ROOT.50plus"
},
"$$REMOVE"
]
}
},
female: {
$push: {
$cond: [
{ $eq: ["$_id.gender", "female"] },
{
"0-30": "$$ROOT.0-30",
"30-50": "$$ROOT.30-50",
"50plus": "$$ROOT.50plus"
},
"$$REMOVE"
]
}
}
}
},
{
$project: {
_id: 0,
nationality: "$_id",
female: { $arrayElemAt: ["$female", 0] }, // Get object from array
male: { $arrayElemAt: ["$male", 0] }
}
}
]);
Тест: MongoDB-Playground