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

MongoDB如何将两个对象数组合并为无重复集合并拆分为单个文档?

实现方案

可以通过MongoDB聚合管道完成需求,具体步骤如下:

聚合管道阶段

  1. 合并两个数组
    使用$concatArrays将directComputers和indirectComputers合并为一个新数组,通过$project输出该数组:
{
  $project: {
    allComputers: { $concatArrays: ["$directComputers", "$indirectComputers"] }
  }
}
  1. 拆分数组为单个文档
    用$unwind把合并后的数组拆分成独立文档:
{ $unwind: "$allComputers" }
  1. 按_id去重
    以_id为分组依据,保留每个电脑的唯一记录:
{
  $group: {
    _id: "$allComputers._id",
    name: { $first: "$allComputers.name" }
  }
}
  1. 还原文档结构
    用$replaceRoot把分组后的字段还原为顶层文档:
{
  $replaceRoot: { newRoot: { _id: "$_id", name: "$name" } }
}

完整聚合管道

将以上阶段与你的facet阶段组合,完整代码如下:

[
  // 你的facet阶段
  {
    $facet: {
      directComputers: [...], // 你的directComputers查询逻辑
      indirectComputers: [...] // 你的indirectComputers查询逻辑
    }
  },
  // 合并数组
  {
    $project: {
      allComputers: { $concatArrays: ["$directComputers", "$indirectComputers"] }
    }
  },
  // 拆分文档
  { $unwind: "$allComputers" },
  // 去重分组
  {
    $group: {
      _id: "$allComputers._id",
      name: { $first: "$allComputers.name" }
    }
  },
  // 还原结构
  {
    $replaceRoot: { newRoot: { _id: "$_id", name: "$name" } }
  }
]

说明

  • $concatArrays负责直接拼接两个数组,暂不处理重复;
  • $unwind拆分后会出现重复的MyComputer_2文档,后续通过分组去重;
  • $group利用_id唯一性去重,$first取该_id对应的第一个name(同一_id的name应一致,用$last也可);
  • $replaceRoot将分组后的嵌套结构转换为你需要的顶层文档格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:50:28