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

MongoDB聚合:根据条件移除嵌套数组中的指定对象

MongoDB聚合:根据条件移除嵌套数组对象中的字段

直接用下面的聚合管道就能实现需求——当freePreview为false时,自动移除对应phone对象里的video字段:

db.collection.aggregate([
  {
    $set: {
      products: {
        $map: {
          input: "$products",
          as: "product",
          in: {
            title: "$$product.title",
            phone: {
              $map: {
                input: "$$product.phone",
                as: "phoneItem",
                in: {
                  $cond: {
                    if: { $eq: ["$$phoneItem.freePreview", false] },
                    then: {
                      title: "$$phoneItem.title",
                      freePreview: "$$phoneItem.freePreview"
                    },
                    else: "$$phoneItem"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
])

步骤拆解:

  • $set阶段:保留文档里的_id、name等字段不变,只针对性更新products数组的内容。
  • 外层$map遍历products数组:逐个处理每个产品对象,保留原title,重点处理内部的phone数组。
  • 内层$map遍历phone数组:对每个手机条目用$cond做条件判断:
    • 若freePreview为false,只返回title和freePreview两个字段,自然排除video;
    • 若freePreview为true,直接返回原条目,保留所有字段。

这种方式无需展开数组再重组,直接通过嵌套遍历+条件过滤完成处理,对嵌套数组的操作效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:45:31