You need to enable JavaScript to run this app. MongoDB 3.4如何统计内嵌数组动态status、category的出现频率
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB 3.4如何统计内嵌数组动态status、category的出现频率

MongoDB 3.4 动态统计status与category聚合方案

完整聚合管道代码

db.collection.aggregate([
  // 拆分tests数组为单条测试记录
  { $unwind: "$tests" },
  // 并行执行status、category两个统计分支
  {
    $facet: {
      // 统计每个id下的status分布
      statusStat: [
        {
          $group: {
            _id: {
              id: "$_id",
              status: "$tests.status"
            },
            count: { $sum: 1 }
          }
        },
        {
          $group: {
            _id: "$_id.id",
            statusList: { $push: { k: "$_id.status", v: "$count" } }
          }
        },
        {
          $project: {
            id: "$_id",
            status: { $arrayToObject: "$statusList" },
            _id: 0
          }
        }
      ],
      // 统计每个id下的category分布
      categoryStat: [
        {
          $group: {
            _id: {
              id: "$_id",
              category: "$tests.category"
            },
            count: { $sum: 1 }
          }
        },
        {
          $group: {
            _id: "$_id.id",
            categoryList: { $push: { k: "$_id.category", v: "$count" } }
          }
        },
        {
          $project: {
            id: "$_id",
            category: { $arrayToObject: "$categoryList" },
            _id: 0
          }
        }
      ]
    }
  },
  // 拆分两个分支的结果数组
  { $unwind: "$statusStat" },
  { $unwind: "$categoryStat" },
  // 按id匹配同一条记录的两个统计结果
  {
    $match: {
      $expr: { $eq: ["$statusStat.id", "$categoryStat.id"] }
    }
  },
  // 输出目标格式
  {
    $project: {
      id: "$statusStat.id",
      status: "$statusStat.status",
      category: "$categoryStat.category",
      _id: 0
    }
  }
])

逻辑说明

  • 所有操作符均兼容MongoDB 3.4版本,$facet、$arrayToObject均为3.4原生支持的能力
  • 用$facet并行跑两个统计分支,避免重复执行多次聚合逻辑
  • status和category的取值完全动态,不需要提前预设枚举值,新增枚举也不需要修改聚合逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 00:27:01