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

如何通过MongoDB聚合合并两个含相似字段的集合?

使用MongoDB聚合合并两个集合(基于字段匹配)

MongoDB聚合完全支持你要的这种合并需求,核心是用$lookup阶段实现集合关联,再通过$mergeObjects把匹配到的字段追加到主文档中。针对你的场景,这里给出具体的聚合管道实现:

假设主集合名为collection1,小集合名为collection2,匹配条件是collection1.title_en = collection2.Name,聚合查询如下:

db.collection1.aggregate([
  // 关联collection2,匹配title_en和Name相等的文档
  {
    $lookup: {
      from: "collection2",
      localField: "title_en",
      foreignField: "Name",
      as: "matched_data"
    }
  },
  // 展开匹配到的数组(如果每个主文档最多匹配一个小文档,保留无匹配的文档)
  {
    $unwind: {
      path: "$matched_data",
      preserveNullAndEmptyArrays: true
    }
  },
  // 合并主文档和匹配到的小文档字段,替换为新的根文档
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: ["$$ROOT", "$matched_data"]
      }
    }
  },
  // 可选:移除多余的matched_data字段和重复的Name字段
  {
    $project: {
      matched_data: 0,
      Name: 0
    }
  }
])

各阶段说明:

  • $lookup:相当于SQL的LEFT JOIN,把collection2中与当前主文档匹配的文档存入matched_data数组。
  • $unwind:将matched_data数组展开为单个文档(如果主文档没有匹配项,preserveNullAndEmptyArrays会保留该文档,不会被过滤)。
  • $replaceRoot + $mergeObjects:把主文档的所有字段和matched_data里的字段合并,生成新的根文档,实现"追加字段"的效果。
  • $project:可选步骤,清理掉中间生成的matched_data字段以及和title_en重复的Name字段。

合并后的示例文档:

{
  "age_rating":"R",
  "age_rating_guide":"17+ (violence & profanity)",
  "average_rating":"82.47",
  "episode_count":26,
  "episode_length":25,
  "poster_image":"https://media.kitsu.io/anime/poster_images/1/original.jpg?1597604210",
  "show_type":"TV",
  "title_en":"Cowboy Bebop",
  "title_ja_jp":"カウボーイビバップ",
  "total_length":650,
  "End_year":1999,
  "Release_season":"Spring",
  "Release_year":1998,
  "Tags":"Action, Adventure, Drama, Sci Fi, Bounty Hunters, Episodic, Noir, Outer Space, Western, Original Work, Drug Use,, Mature Themes,, Nudity,, Violence"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 23:19:01