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

MongoDB脚本遇null对象生成空对象的修复方法咨询

解决MongoDB脚本中situation为null时被转为空对象的问题

问题根源

你的原脚本里,$cond仅判断了situation不等于undefined,但当situation是null时,依然会进入分支执行$mergeObjects操作。由于$$this.situation为null,合并后会生成空对象,这就是不符合预期的原因。

修正方案

需要同时把null和undefined排除在重命名逻辑之外,仅当situation是有效非空对象时才执行字段重命名,其他情况(包括null、undefined)直接保留原值。

修正后的核心代码

{
  serviceAgreementRefList: {
    $map: {
      input: "$$this.relatedJson.serviceAgreementRefList",
      in: {
        $mergeObjects: [
          "$$this",
          {
            $cond: [
              // 同时排除undefined和null,仅处理非空的situation对象
              { $and: [
                  { $ne: ["$$this.situation", undefined] },
                  { $ne: ["$$this.situation", null] }
                ]
              },
              {
                situation: {
                  $mergeObjects: [
                    "$$this.situation",
                    { color: "$$this.situation.colour" },
                    // 可选:移除原colour字段,避免冗余
                    { $unset: "colour" }
                  ]
                }
              },
              // 不满足条件时,直接保留原situation值(null/undefined都不变)
              { situation: "$$this.situation" }
            ]
          }
        ]
      }
    }
  }
}

关键细节

  1. 条件判断:用$and组合两个$ne,精准筛选出需要处理的非空situation对象,避免null进入重命名逻辑。
  2. 原值保留:$cond的else分支直接返回原situation,确保null和undefined都不会被修改。
  3. 可选优化:加上$unset: "colour"可以删掉原来的colour字段,避免同一个字段两种拼写并存,让数据更整洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 05:01:06