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

如何在MongoDB聚合管道中提取首个文档的children数组转为输出文档

解决方法

在$graphLookup之后加个$limit: 1阶段,只保留第一个文档,再执行后续的$unwind和$replaceRoot操作,从源头避免重复数据,完整聚合管道如下:

完整代码示例

{ $match: { from: "some_root" } },
{
  $graphLookup: {
    from: "connections",
    startWith: "$to",
    connectFromField: "to",
    connectToField: "from",
    as: "children",
    depthField: "depth",
    maxDepth: 100
  },
},
{ $limit: 1 }, // 只留首个文档,杜绝后续处理重复数据
{ $unwind: { path: "$children" } },
{ $replaceRoot: { newRoot: "$children" } }

原理说明

  • $limit: 1直接截取$graphLookup输出结果的第一个文档,后续的$unwind只会处理这一个文档内的children数组,不会生成重复的子文档。
  • 这种方式比用$group事后去重高效得多——既然能从源头避免重复,就没必要多做一轮去重计算。

效果验证

针对你给出的$graphLookup输出:

{
  _id: 1,
  children: [
    { _id: 10 },
    { _id: 11 }
  ]
},
{
  _id: 2,
  children: [
    { _id: 10 },
    { _id: 11 }
  ]
}

经过$limit:1后,仅保留_id:1的文档,再执行后续步骤,就能得到目标结果:

{ _id: 10 },
{ _id: 11 }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 03:39:59