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

Mongo聚合管道添加条件字段:根据数组是否非空设置type字段

解决Mongo聚合管道添加type字段的方案

这需求用MongoDB聚合的$addFields配合嵌套的$cond就能完美实现,逻辑清晰还容易维护,直接把下面这个阶段加到你现有管道的最后就行:

{
  $addFields: {
    type: {
      $cond: {
        if: { $and: [{ $gt: [{ $size: "$feature1" }, 0] }, { $gt: [{ $size: "$feature2" }, 0] }] },
        then: "back",
        else: {
          $cond: {
            if: { $gt: [{ $size: "$feature2" }, 0] },
            then: "front",
            else: "none"
          }
        }
      }
    }
  }
}

逻辑拆解:

  • 首先用外层$cond判断feature1和feature2都有元素的情况:通过$size获取数组长度,用$gt判断是否大于0,再用$and把两个条件组合起来,满足就返回'back'。
  • 如果不满足第一个条件,就进入内层$cond,判断只有feature2有元素的情况,满足返回'front'。
  • 剩下的所有情况(两个数组都空,或者只有feature1有元素),统一返回'none'。

测试场景验证:

  • 输入:{ feature1: [{random: 125}], feature2: [{a:"fsfs", val: [125]}] } → 输出type为'back'
  • 输入:{ feature1: [], feature2: [{a:"fsfs", val: [125]}] } → 输出type为'front'
  • 输入:{ feature1: [{random: 125}], feature2: [] } → 输出type为'none'
  • 输入:{ feature1: [], feature2: [] } → 输出type为'none'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:26:20