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

MongoDB聚合管道$group阶段后如何过滤嵌套数组处理无contents的section

问题原因

你开启了$unwind的preserveNullAndEmptyArrays: true参数,没有contents字段的section在展开后,sections.contents相关字段会变为null,后续的分组阶段会将这些null值组装成无效的contents元素,就出现了你遇到的多余空结构问题。
你之前写的过滤逻辑只针对tasks数组,没有过滤掉整个无效的content对象,所以不会生效。

解决方案

在你现有的最后一个$group阶段之后,新增如下$addFields阶段即可:

{
  $addFields: {
    sections: {
      $map: {
        input: "$sections",
        as: "section",
        in: {
          $cond: {
            // 校验当前section是否存在有效content
            if: {
              $gt: [
                {
                  $size: {
                    $filter: {
                      input: "$$section.contents",
                      as: "content",
                      // 以contentId不为null作为有效判断标准,你也可以根据业务调整判断规则
                      cond: { $ne: ["$$content.contentId", null] }
                    }
                  }
                },
                0
              ]
            },
            // 存在有效content:过滤掉无效content项后保留contents字段
            then: {
              $mergeObjects: [
                "$$section",
                {
                  contents: {
                    $filter: {
                      input: "$$section.contents",
                      as: "content",
                      cond: { $ne: ["$$content.contentId", null] }
                    }
                  }
                }
              ]
            },
            // 无有效content:仅保留section基础字段,移除contents字段
            else: {
              sectionId: "$$section.sectionId",
              sectionName: "$$section.sectionName"
            }
          }
        }
      }
    }
  }
}

该逻辑会自动判断每个section的contents是否存在有效内容,不存在就直接删除contents字段,完全符合你期望的输出结构。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 05:36:01