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

如何使用MongoDB的$graphLookup构建关联文档链表并返回指定顺序数组

MongoDB 递归查询构建引用链表实现方案

你可以通过补充$graphLookup层级记录、排序、数组合并步骤实现需求,完整聚合语句如下:

db.collection.aggregate([
  // 匹配链表起始节点,此处以postId=4作为链表起点
  { $match: { postId: 4 } },
  {
    "$graphLookup": {
      "from": "collection",
      "startWith": "$parent",
      "connectFromField": "parent",
      "connectToField": "postId",
      "as": "revisions",
      "depthField": "level" // 新增字段记录节点递归深度,用于后续排序
    }
  },
  // 将起始节点本身合并到链路数组中
  {
    $addFields: {
      revisions: {
        $concatArrays: [
          [{ postId: "$postId", level: -1 }],
          "$revisions"
        ]
      }
    }
  },
  // 拆分数组便于排序
  { $unwind: "$revisions" },
  // 按层级升序排序,得到 4->3->2->1 的顺序
  { $sort: { "revisions.level": 1 } },
  // 提取postId组成结果数组
  {
    $group: {
      _id: "$_id",
      linkedList: { $push: "$revisions.postId" }
    }
  }
])

执行后输出的linkedList字段值即为你需要的[4,3,2,1]格式。

如果你需要生成4 -> 3 -> 2 -> 1格式的字符串,可以在上述聚合最后追加如下步骤:

{
  $addFields: {
    linkedStr: {
      $reduce: {
        input: "$linkedList",
        initialValue: "",
        in: {
          $cond: {
            if: { $eq: ["$$value", ""] },
            then: { $toString: "$$this" },
            else: { $concat: ["$$value", " -> ", { $toString: "$$this" }] }
          }
        }
      }
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:27:03