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"] ] } } } } ] } } } ] } } } } } ])
代码说明
- 外层
$reduce遍历最顶层的_a数组,初始化累加值为0 - 中层
$reduce遍历每个_a元素下的_p数组,持续累加计数 - 最内层处理:
- 用
$toLower把lang统一转为小写,避免逐个判断大小写变体 - 通过
$filter筛选出lang小写后等于"en"的t元素 - 用
$size获取筛选后的数组长度,加入当前累加值
- 用
- 最终
totalCount即为符合条件的元素总数,对应预期的7
内容的提问来源于stack exchange,提问作者R2D2
相关产品推荐
相关产品推荐

