You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MongoDB中计算指定年龄人数占总人数的百分比

实现方案

你可以通过 MongoDB 的 $facet 聚合阶段同时完成全量用户数统计和指定年龄用户数统计,再计算百分比,完整聚合语句如下:

db.collection.aggregate([
  {
    $facet: {
      // 分支1:统计全集合总用户数
      total_count: [
        { $count: "total" }
      ],
      // 分支2:统计指定年龄的用户数,这里示例目标年龄为41,可按需修改
      target_age_count: [
        { $match: { age: 41 } },
        { $count: "count" }
      ]
    }
  },
  // 提取数组中的统计值
  {
    $project: {
      total: { $arrayElemAt: ["$total_count.total", 0] },
      target_count: { $arrayElemAt: ["$target_age_count.count", 0] },
      age: { $literal: 41 }
    }
  },
  // 计算百分比,示例保留2位小数,可按需调整精度
  {
    $project: {
      _id: 0,
      age: 1,
      percentage_with_age: {
        $round: [
          { $multiply: [ { $divide: ["$target_count", "$total"] }, 100 ] },
          2
        ]
      }
    }
  }
])

逻辑说明

  • $facet 可以在同一次聚合中并行执行多个独立的聚合分支,不会互相干扰,刚好满足你同时需要总用户数和指定年龄用户数的需求
  • 如果需要处理无匹配年龄、总用户数为0的异常场景,可以加 $cond 做兼容判断,避免除零或者空值报错。

内容的提问来源于stack exchange,提问作者Piero.Sgri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 04:45:02