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

MongoDB聚合:根据字段是否存在执行条件$lookup查询

MongoDB聚合查询:按需关联集合保留或补充history字段

我有两个集合collection1和collection2,数据结构如下:

// collection1 数据

[
  { "_id": 100, "text": "i am good", "history":[{"date":"2023-6-1", "updated":"2023-6-2"}] },
  { "_id": 101, "text": "i am naughty"}
]

// collection2 数据

[
  { "_id": 1, "collection1Id":100, "date":"2023-6-1", "updated":"2023-6-2" },
  { "_id": 2, "collection1Id":101, "date":"2023-7-3", "updated":"2023-7-5" }
]

需求是:对collection1执行聚合查询,当文档不存在history字段时,关联collection2获取对应数据作为history;如果已经存在history字段,则直接保留原字段内容。预期输出如下:

[
  { "_id": 100, "text": "i am good", "history":[{"date":"2023-6-1", "updated":"2023-6-2"}] },
  { "_id": 101, "text": "i am naughty", "history":[{"_id": 2, "collection1Id": 101, "date":"2023-7-3", "updated":"2023-7-5"}] }
]

解决方案

通过$lookup结合条件判断可以实现该需求,具体聚合查询代码如下:

db.collection1.aggregate([
  // 关联collection2,将匹配数据存入临时字段
  {
    $lookup: {
      from: "collection2",
      localField: "_id",
      foreignField: "collection1Id",
      as: "matchedHistory"
    }
  },
  // 按条件替换或保留history字段
  {
    $addFields: {
      history: {
        $cond: {
          if: { $exists: ["$history", true] },
          then: "$history",
          else: "$matchedHistory"
        }
      }
    }
  },
  // 清理临时字段
  {
    $project: {
      matchedHistory: 0
    }
  }
])

步骤说明

  1. $lookup阶段:将collection1的_id与collection2的collection1Id做关联,把匹配到的结果存入临时字段matchedHistory。
  2. $addFields阶段:用$cond配合$exists判断文档是否存在history字段:
    • 存在则直接保留原history数据;
    • 不存在则用matchedHistory的值填充history字段。
  3. $project阶段:移除临时字段matchedHistory,让输出结构更简洁。

执行以上聚合查询后,就能得到符合预期的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 00:32:42