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

MongoDB 如何从集合中统计0-18、19-24等各年龄段的人数数据

MongoDB分年龄段统计实现方案

核心实现逻辑分为三步:

  • 将字符串格式的出生日期dob转换为MongoDB标准日期类型
  • 计算出生日期到当前时间的实际年龄
  • 按要求的四个年龄段分组统计对应人数

以下是可直接运行的聚合查询语句:

db.collection.aggregate([
  // 转换dob字符串为日期类型
  {
    $addFields: {
      birthDate: {
        $dateFromString: {
          dateString: "$dob",
          format: "%d-%m-%Y" // 适配示例中日-月-年的日期存储格式
        }
      }
    }
  },
  // 计算实际年龄
  {
    $addFields: {
      age: {
        $dateDiff: {
          startDate: "$birthDate",
          endDate: "$$NOW",
          unit: "year"
        }
      }
    }
  },
  // 分区间统计人数
  {
    $facet: {
      "0-18岁": [
        { $match: { age: { $lte: 18 } } },
        { $count: "total" }
      ],
      "19-24岁": [
        { $match: { age: { $gte: 19, $lte: 24 } } },
        { $count: "total" }
      ],
      "25-34岁": [
        { $match: { age: { $gte: 25, $lte: 34 } } },
        { $count: "total" }
      ],
      "35岁及以上": [
        { $match: { age: { $gte: 35 } } },
        { $count: "total" }
      ]
    }
  },
  // 格式化输出,空区间默认补0
  {
    $project: {
      "0-18岁": { $ifNull: [{ $first: "$0-18岁.total" }, 0] },
      "19-24岁": { $ifNull: [{ $first: "$19-24岁.total" }, 0] },
      "25-34岁": { $ifNull: [{ $first: "$25-34岁.total" }, 0] },
      "35岁及以上": { $ifNull: [{ $first: "$35岁及以上.total" }, 0] }
    }
  }
])

版本兼容说明

如果你使用的MongoDB版本低于5.0,不支持$dateDiff算子,可以替换为以下逻辑计算年龄:

age: {
  $subtract: [
    { $year: "$$NOW" },
    { $year: "$birthDate" }
  ]
}

内容的提问来源于stack exchange,提问作者simon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:54:01