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

MongoDB聚合中如何根据匹配条件为数组元素对应类型添加新字段?

可以实现!这里是正确的聚合查询方案

你的问题核心在于直接对数组字段$objectives.type使用$eq判断——因为$objectives.type返回的是一个包含所有type值的数组(比如["LESSON", "MODULE"]),而不是单个元素的type,所以$cond的判断逻辑永远不成立,才会一直返回False。

下面是可以一次性实现需求的聚合管道,我会分步骤说明逻辑:

db.account.aggregate([
  {
    $project: {
      _id: 0,
      id: 1,
      courseId: 1,
      objectives: 1,
      // 提取LESSON类型对应的id
      lessonId: {
        $ifNull: [
          {
            $first: {
              $map: {
                input: { $filter: { input: "$objectives", cond: { $eq: ["$$this.type", "LESSON"] } } },
                in: "$$this.id"
              }
            }
          },
          false
        ]
      },
      // 提取MODULE类型对应的id
      moduleId: {
        $ifNull: [
          {
            $first: {
              $map: {
                input: { $filter: { input: "$objectives", cond: { $eq: ["$$this.type", "MODULE"] } } },
                in: "$$this.id"
              }
            }
          },
          false
        ]
      }
    }
  }
])

关键步骤解释:

  • $filter:从objectives数组中筛选出type匹配目标值(比如LESSON)的元素,得到一个只包含对应类型的子数组。
  • $map:把筛选后的子数组转换成仅包含id字段的数组,比如从[{ "type": "LESSON", "id": "dfhxytd" }]变成["dfhxytd"]。
  • $first:从这个id数组中取出第一个值(假设每个type在objectives里只会出现一次)。
  • $ifNull:如果某个类型不存在(比如没有LESSON项),就返回false作为默认值,和你最初的尝试逻辑对齐。

执行这个聚合后,就能得到你期望的输出结构:

{ "id" : "yzes547", "courseId" : "aw4a34y7", "objectives" : [ { "type" : "LESSON", "id" : "dfhxytd" }, { "type" : "MODULE", "id" : "rgzeerp" } ], "lessonId": "dfhxytd", "moduleId": "rgzeerp" }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 11:23:16