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

MongoDB:无需unwind统计嵌套数组指定值的数量

无需$unwind的MongoDB嵌套数组统计方案

针对你需要统计集合中c.d.b.a等于2的元素数量的需求,以下是不依赖$unwind的聚合管道方案,能避免大数据量下的性能损耗:

聚合查询代码

db.collection.aggregate([
  // 单文档内计算当前文档中符合条件的元素数量
  {
    $project: {
      count: {
        $reduce: {
          input: "$c",
          initialValue: 0,
          in: {
            $add: [
              "$$value",
              {
                $reduce: {
                  input: "$$this.d",
                  initialValue: 0,
                  in: {
                    $add: [
                      "$$value",
                      // 筛选b数组中a=2的元素并统计数量
                      {
                        $size: {
                          $filter: {
                            input: "$$this.b",
                            cond: { $eq: ["$$this.a", 2] }
                          }
                        }
                      }
                    ]
                  }
                }
              }
            ]
          }
        }
      }
    }
  },
  // 汇总所有文档的统计结果
  {
    $group: {
      _id: null,
      a: { $sum: "$count" }
    }
  },
  // 调整输出格式为预期的{"a":3}
  {
    $project: {
      _id: 0,
      a: 1
    }
  }
])

方案说明

  • 用两层$reduce分别遍历嵌套的c和d数组,逐层累计符合条件的元素数量
  • 用$filter精准筛选b数组中a等于2的元素,再通过$size直接获取该子集的长度
  • 全程在单文档维度完成数组计算,不会像$unwind那样生成大量中间文档,在数据量极大时能显著提升查询效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 06:54:56