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

MongoDB三级嵌套数组按lang条件计数优化问询

解决方案

核心逻辑

通过嵌套$reduce遍历三级嵌套数组,在最内层对t数组用$filter匹配lang为EN/en/En的元素,再通过$size统计符合条件的元素数量,最后逐层累加得到总计数,全程无需使用$unwind。

完整聚合代码

db.collection.aggregate([
  {
    $project: {
      totalCount: {
        $reduce: {
          input: "$_a",
          initialValue: 0,
          in: {
            $add: [
              "$$value",
              {
                $reduce: {
                  input: "$$this._p",
                  initialValue: 0,
                  in: {
                    $add: [
                      "$$value",
                      {
                        $size: {
                          $filter: {
                            input: "$$this.s.c.t",
                            cond: {
                              $in: [
                                { $toLower: "$$this.lang" },
                                ["en"]
                              ]
                            }
                          }
                        }
                      }
                    ]
                  }
                }
              }
            ]
          }
        }
      }
    }
  }
])

代码说明

  1. 外层$reduce遍历最顶层的_a数组,初始化累加值为0
  2. 中层$reduce遍历每个_a元素下的_p数组,持续累加计数
  3. 最内层处理:
    • 用$toLower把lang统一转为小写,避免逐个判断大小写变体
    • 通过$filter筛选出lang小写后等于"en"的t元素
    • 用$size获取筛选后的数组长度,加入当前累加值
  4. 最终totalCount即为符合条件的元素总数,对应预期的7

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:05:45