MongoDB聚合查询如何去除返回结果数组中的空花括号对象
空对象产生原因
你在$unwind ARef和BRef时开启了preserveNullAndEmptyArrays: true,所以来自A分支的聚合结果BRef字段为null,来自B分支的聚合结果ARef字段为null。在$group阶段执行$push操作时,字段为null的条目会生成没有对应属性的空对象,最终出现在输出数组中。
解决方法
方案1:末尾新增过滤阶段(改造成本最低)
在你现有聚合管道的最后新增一个$project阶段,过滤所有数组中的空对象即可:
{ $project: { A_set: { $filter: { input: "$A_set", cond: { $ne: [ "$$this", {} ] } } }, A_count_set: { $filter: { input: "$A_count_set", cond: { $ne: [ "$$this", {} ] } } }, B_set: { $filter: { input: "$B_set", cond: { $ne: [ "$$this", {} ] } } }, B_count_set: { $filter: { input: "$B_count_set", cond: { $ne: [ "$$this", {} ] } } } } }
方案2:优化$group逻辑(性能更优)
直接修改现有$group阶段的配置,使用MongoDB内置的$$REMOVE变量,只有对应字段非空时才将对象推入数组,从根源避免空对象生成:
{ $group: { _id: "$QRef.text", A_set: { $push: { $cond: [ { $ne: [ "$ARef.value", null ] }, { A: "$ARef.value" }, "$$REMOVE" ] } }, A_count_set: { $push: { $cond: [ { $ne: [ "$combined_group.A_count", null ] }, { A_count: "$combined_group.A_count" }, "$$REMOVE" ] } }, B_set: { $push: { $cond: [ { $ne: [ "$BRef.value", null ] }, { B: "$BRef.value" }, "$$REMOVE" ] } }, B_count_set: { $push: { $cond: [ { $ne: [ "$combined_group.B_count", null ] }, { B_count: "$combined_group.B_count" }, "$$REMOVE" ] } } } }
注意:如果你的MongoDB版本低于3.6,不支持
$$REMOVE变量,请使用方案1。
内容的提问来源于stack exchange,提问作者femtowatts
相关产品推荐
相关产品推荐

