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

如何在MongoDB集合中查找重复项并合并指定platforms字段

实现方案

你可以通过$group分组收集同name数据,再拼接platforms数组实现需求,聚合语句如下:

db.titles.aggregate([
  {
    $group: {
      _id: "$name",
      // 保留同组第一条的_id,可按需替换为$last取最后一条的_id
      docId: { $first: "$_id" },
      // 收集同组所有文档的platforms字段,得到二维数组
      platformsGroup: { $push: "$platforms" },
      // 其他需要保留的非重复字段可在此处用$first/$last取值
      // exampleField: { $first: "$exampleField" }
    }
  },
  {
    $project: {
      _id: "$docId",
      name: "$_id",
      // 将二维platforms数组拍平为一维,合并所有平台数据
      platforms: {
        $reduce: {
          input: "$platformsGroup",
          initialValue: [],
          in: { $concatArrays: ["$$value", "$$this"] }
        }
      }
      // 其他需要输出的字段可在此处声明
      // exampleField: 1
    }
  },
  // 若仅需要保留存在重复的name分组,可新增以下match阶段
  // { $match: { count: { $gt: 1 } } }
], { allowDiskUse: true })

补充说明

  1. 如果你需要合并后的platforms数组不存在完全重复的平台对象,可以把$concatArrays替换为$setUnion,会自动对平台对象去重
  2. 你给出的示例中两条数据的name字段分别为Foo1和Foo2,属于不同分组,若要得到你贴出的预期输出,只需将两条数据的name值设为相同即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 09:06:02