如何用MongoDB聚合框架按性别实现客户年龄分布统计?
如何在MongoDB聚合中结合性别与年龄分桶生成人口统计报告
当然可以实现!其实你只需要在聚合管道里调整几步,就能把性别维度和年龄分桶完美结合起来。我给你两种实用的方案,你可以根据自己的报告需求来选:
方案1:先按性别分组,再统计各性别内的年龄分布
这种方案适合你想单独看男性、女性各自的年龄分段情况,比如“男性里20-30岁有多少人”这类需求。
聚合管道代码如下:
db.customers.aggregate([ // 第一步:按性别分组,把同性别用户的年龄收集到数组里 { $group: { _id: "$gender", ages: { $push: "$age" } } }, // 第二步:对每个性别下的年龄数组做分桶统计 { $project: { gender: "$_id", ageBuckets: { $bucket: { input: "$ages", boundaries: [0, 20, 30, 40, 50, 60, 100], // 自定义年龄区间,可按需调整 default: "60+", output: { count: { $sum: 1 } } } }, _id: 0 } } ])
示例输出
[ { "gender": "male", "ageBuckets": [ { "_id": 0, "count": 120 }, { "_id": 20, "count": 345 }, { "_id": 30, "count": 280 }, { "60+": 95 } ] }, { "gender": "female", "ageBuckets": [ { "_id": 0, "count": 110 }, { "_id": 20, "count": 320 }, { "_id": 30, "count": 295 }, { "60+": 110 } ] } ]
方案2:先按年龄分桶,再统计每个桶内的性别分布
如果你的需求是看每个年龄段里男女的占比,比如“30-40岁区间里男女人数分别是多少”,那这个方案更合适。
聚合管道代码如下:
db.customers.aggregate([ // 第一步:按年龄分桶 { $bucket: { _id: { $switch: { branches: [ { case: { $lte: ["$age", 20] }, then: "0-20" }, { case: { $lte: ["$age", 30] }, then: "21-30" }, { case: { $lte: ["$age", 40] }, then: "31-40" }, { case: { $lte: ["$age", 50] }, then: "41-50" }, { case: { $lte: ["$age", 60] }, then: "51-60" } ], default: "60+" } }, // 第二步:在每个桶内统计男女人数 output: { total: { $sum: 1 }, maleCount: { $sum: { $cond: [{ $eq: ["$gender", "male"] }, 1, 0] } }, femaleCount: { $sum: { $cond: [{ $eq: ["$gender", "female"] }, 1, 0] } } } } }, // 可选:按年龄段排序,让结果更规整 { $sort: { "_id": 1 } } ])
示例输出
[ { "_id": "0-20", "total": 230, "maleCount": 120, "femaleCount": 110 }, { "_id": "21-30", "total": 665, "maleCount": 345, "femaleCount": 320 }, { "_id": "31-40", "total": 575, "maleCount": 280, "femaleCount": 295 }, { "_id": "60+", "total": 205, "maleCount": 95, "femaleCount": 110 } ]
小提示
- 你可以根据实际需求调整
boundaries(方案1)或者$switch的区间(方案2),比如把区间设成10岁一档或者其他维度。 - 如果还有其他字段需要统计,比如每个分组的平均年龄,只需要在
output里加对应的聚合表达式就行,比如avgAge: { $avg: "$age" }。
内容的提问来源于stack exchange,提问作者Daksh
相关产品推荐
相关产品推荐

