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

MongoDB聚合:如何将$set生成的[{}]替换为空数组?

解决方法

在生成buyer字段的$set阶段中,增加条件判断逻辑,当嵌套lookup返回的buyers为null或空数组时,直接返回空数组,否则再执行映射转换:

{
  $set: {
    buyer: {
      $cond: {
        if: { $or: [{ $eq: ["$buyers", []] }, { $eq: ["$buyers", null] }] },
        then: [],
        else: {
          $map: {
            input: "$buyers",
            as: "b",
            in: {
              name: "$$b.name",
              age: "$$b.age"
            }
          }
        }
      }
    }
  }
}

原理是通过$cond结合$or判断buyers的状态:

  • 若buyers是空数组或null,直接输出空数组
  • 若buyers有有效数据,再用$map提取需要的字段

这样就能避免原本空状态下返回[{}]的问题,符合预期结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 07:20:13