MongoDB聚合中带条件$reduce拆分extra数组为cheap、exp数组的问题
原聚合代码存在的核心问题
$reduce语法结构错位:$reduce要求迭代执行逻辑必须写在专属的in字段下,原代码错误将in嵌套在$cond的then/else分支内,不符合聚合操作符的语法校验规则- 遍历入参错误:
$reduce的input写为['$extra'],相当于把原本的一维对象数组二次嵌套为仅包含一个元素(整个extra数组)的二维数组,导致迭代逻辑只会执行1次,无法逐次处理数组内的每个对象 - 类型校验错误:
$concatArrays要求所有入参必须是数组类型,原代码中直接将单个遍历对象$$this作为入参传入,会直接触发类型不匹配报错 - 属性判断逻辑不准确:使用
$$this.plus == null无法准确识别“对象不存在plus属性”的场景——MongoDB中对不存在的字段做取值会返回缺失值,和字面量null并不完全等价,当对象存在plus: null的场景时会出现误判 - 分支返回值不完整:每次迭代不管走哪个判断分支,都需要同步更新
cheap和exp两个数组的值,不能只返回单个数组字段,否则最终结果结构会缺失另一个数组
修正后的聚合实现
基于$reduce的拆分逻辑
完全匹配最初的实现思路,修正后的可运行代码如下:
db.collection.aggregate([ { $project: { splitResult: { $reduce: { input: "$extra", // 直接遍历原始一维extra数组,避免额外嵌套 initialValue: { cheap: [], exp: [] }, // 迭代逻辑统一写在in字段下 in: { $cond: { // 判断当前对象是否存在plus属性 if: { $ne: [ { $type: "$$this.plus" }, "missing" ] }, // 存在plus属性:加入exp数组,cheap数组保持原值 then: { cheap: "$$value.cheap", exp: { $concatArrays: ["$$value.exp", [ "$$this" ]] } }, // 不存在plus属性:加入cheap数组,exp数组保持原值 else: { cheap: { $concatArrays: ["$$value.cheap", [ "$$this" ]] }, exp: "$$value.exp" } } } } } } }, // 可选:打平嵌套结构,直接输出顶层cheap、exp字段 { $project: { _id: 0, cheap: "$splitResult.cheap", exp: "$splitResult.exp" } } ])
针对提供的示例数据,运行后会输出:
{ "cheap": [ { "description": "sole", "type": "interior" }, { "description": "logo", "type": "exterior" } ], "exp": [ { "description": "laces", "type": "exterior", "plus": "200" }, { "description": "stud", "type": "exterior", "plus": "450" } ] }
更简洁的$filter实现方案
如果不需要在一次迭代中同时完成两个数组的拆分,直接对原extra数组做两次独立过滤即可,代码可读性更强,且性能和$reduce方案基本一致:
db.collection.aggregate([ { $project: { _id: 0, exp: { $filter: { input: "$extra", as: "item", cond: { $ne: [ { $type: "$$item.plus" }, "missing" ] } } }, cheap: { $filter: { input: "$extra", as: "item", cond: { $eq: [ { $type: "$$item.plus" }, "missing" ] } } } } } ])
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

