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

如何在MongoDB中使用aggregate与$lookup合并两个集合的指定字段

实现方案

你可以通过MongoDB聚合管道的$lookup+$unwind+$project几个阶段组合实现需求,完整的聚合查询语句如下:

db.collection1.aggregate([
  // 以name作为关联键关联collection2
  {
    $lookup: {
      from: "collection2",
      localField: "name",
      foreignField: "name",
      as: "extraInfo"
    }
  },
  // 过滤掉没有匹配到的记录,仅保留两边都匹配的结果
  {
    $match: {
      extraInfo: { $ne: [] }
    }
  },
  // 把lookup返回的数组拆为单个对象(每个name仅对应一条collection2记录)
  {
    $unwind: "$extraInfo"
  },
  // 整理输出字段,仅保留需要的内容
  {
    $project: {
      _id: 0, // 不需要输出_id可关闭该字段
      name: 1,
      city: 1,
      education: "$extraInfo.education",
      occupation: "$extraInfo.occupation"
    }
  }
])

可选优化方案(MongoDB 5.0+版本适用)

如果你的数据库版本支持$lookup管道语法,可以在关联阶段就过滤不需要的字段,性能更高,也可以省去手动逐个指定提取字段的步骤:

db.collection1.aggregate([
  {
    $lookup: {
      from: "collection2",
      localField: "name",
      foreignField: "name",
      // 关联阶段直接过滤仅保留需要的字段
      pipeline: [
        { $project: { education: 1, occupation: 1, _id: 0 } }
      ],
      as: "extraInfo"
    }
  },
  { $match: { extraInfo: { $ne: [] } } },
  { $unwind: "$extraInfo" },
  // 把关联到的字段直接合并到根文档
  { $replaceRoot: { newRoot: { $mergeObjects: [ "$$ROOT", "$extraInfo" ] } } },
  // 移除多余的中间字段
  { $project: { extraInfo: 0, _id: 0 } }
])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 00:06:03