MongoDB聚合更新$in参数错误及数组拼接逻辑实现求助
解决MongoDB聚合更新中$in表达式报错及逻辑不生效问题
问题概述
报错信息:
MongoServerError: Invalid $set :: caused by :: Expression $in takes exactly 2 arguments. 1 were passed in
原始文档数据:
{ "offers" : [ { "name" : "min", "prices" : [ 8, 15, 18 ] }, { "name" : "max", "prices" : [ 9, 11, 18 ] } ], "nl" : [ 2, 4, 6, 7 ] }
需求:根据nl字段是否包含7,对offers数组进行操作:若包含则保持offers不变,否则向offers中添加指定对象{"name": "minimal", "prices": []}。
现有写法的错误分析
第一种写法报错原因
[ { $set: { offers: { $cond: { if: { "nl": {$in: [7]} }, then: { $concatArrays: ["$offers", []] }, else: { $concatArrays: ["$offers", [{ "name" : "minimal", "prices" : [] }]] } } } } } ]
$in表达式语法错误:$in必须传入两个参数,格式为$in: [要查找的元素, 目标数组字段],此处仅传了[7]一个参数,触发参数数量报错。- 条件格式错误:
if字段下直接用"nl": {...}的写法不符合聚合表达式规范,应直接使用$in表达式作为判断条件。
第二种写法不生效原因
[ { $set: { offers: { $cond: { if: { $in: ["$nl", 7] }, then: { $concatArrays: ["$offers", []] }, else: { $concatArrays: ["$offers", [{ "name" : "minimal", "prices" : [] }]] } } } } } ]
$in参数顺序颠倒:正确顺序是$in: [要查找的元素, 目标数组],此处写成了["$nl", 7],导致判断逻辑完全错误,条件永远不成立,因此无法触发预期分支。
正确的聚合更新写法
优化后的写法,修正$in参数顺序,同时简化then分支逻辑(直接返回原数组即可,无需拼接空数组):
[ { $set: { offers: { $cond: { if: { $in: [7, "$nl"] }, then: "$offers", else: { $concatArrays: ["$offers", [{ "name": "minimal", "prices": [] }]] } } } } } ]
说明
$in: [7, "$nl"]:正确判断7是否存在于nl数组中then: "$offers":直接返回原offers数组,保持不变else分支:使用$concatArrays将指定对象追加到offers数组末尾
内容的提问来源于stack exchange,提问作者Md Nazmul Islam
相关产品推荐
相关产品推荐

