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

如何扩展MongoDB聚合管道提取refs唯一值并查询对应文档

MongoDB聚合管道扩展方案

需求实现步骤

1. 收集refs字段的所有唯一值

在现有聚合管道的输出之后,添加以下阶段提取并去重refs中的值:

方式一:$unwind + $group(直观易懂)

// 展开refs数组为单个元素
{ $unwind: "$refs" },
// 分组收集唯一值
{
  $group: {
    _id: null,
    uniqueRefs: { $addToSet: "$refs" }
  }
}

执行后得到包含唯一值集合的文档:

[ { "_id": null, "uniqueRefs": [1, 2, 3] } ]

方式二:$reduce + $setUnion(无需展开数组,性能更优)

// 收集所有refs数组到一个集合中
{
  $group: {
    _id: null,
    allRefs: { $push: "$refs" }
  }
},
// 通过集合合并去重得到唯一值
{
  $project: {
    uniqueRefs: {
      $reduce: {
        input: "$allRefs",
        initialValue: [],
        in: { $setUnion: ["$$value", "$$this"] }
      }
    }
  }
}

此方式同样能得到uniqueRefs: [1,2,3],且避免了数组展开操作。


2. 返回_id匹配唯一值集合的文档

在得到唯一值集合后,通过$lookup关联原集合,再提取匹配的文档:

继续添加以下聚合阶段:

// 关联原集合,匹配_id在uniqueRefs中的文档
{
  $lookup: {
    from: "yourCollection", // 替换为你的实际集合名称
    localField: "uniqueRefs",
    foreignField: "_id",
    as: "matchedDocs"
  }
},
// 展开匹配到的文档数组
{ $unwind: "$matchedDocs" },
// 将匹配的文档作为根文档返回
{ $replaceRoot: { newRoot: "$matchedDocs" } }

执行完成后,最终会返回原集合中_id为1、2、3的三个文档。


完整扩展后的聚合管道(以方式一为例)

// 现有聚合管道...
{ $unwind: "$refs" },
{
  $group: {
    _id: null,
    uniqueRefs: { $addToSet: "$refs" }
  }
},
{
  $lookup: {
    from: "yourCollection",
    localField: "uniqueRefs",
    foreignField: "_id",
    as: "matchedDocs"
  }
},
{ $unwind: "$matchedDocs" },
{ $replaceRoot: { newRoot: "$matchedDocs" } }

内容的提问来源于stack exchange,提问作者Mo B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 05:45:43