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

MongoDB 3.4聚合查询:关联两集合并仅提取userId字段

MongoDB 3.4聚合查询:关联集合并提取指定字段

集合结构

req集合

{
   reqId: "A123",
   status: "1",
   location: "hyd"
}

reqUser集合

{
   req: "A123",
   userId: "U1787",
   designation: "employee"
}

需求

过滤req集合中location="hyd"的文档,通过reqId关联reqUser集合,最终只保留reqId、status和userId字段,输出格式如下:

{
   reqId: "A123",
   status: "1",
   userId: "U1787"
}

解决方案

在现有聚合流程基础上,需在$lookup后添加$unwind展开关联数组,再通过$project提取指定字段。完整聚合管道如下:

db.req.aggregate([
  // 过滤location为hyd的文档
  { $match: { location: "hyd" } },
  // 关联reqUser集合,匹配条件为req.reqId = reqUser.req
  {
    $lookup: {
      from: "reqUser",
      localField: "reqId",
      foreignField: "req",
      as: "reqUser"
    }
  },
  // 展开reqUser数组($lookup返回数组,即使仅匹配一条数据)
  { $unwind: "$reqUser" },
  // 投影指定输出字段,提取reqUser中的userId
  {
    $project: {
      _id: 0,
      reqId: 1,
      status: 1,
      userId: "$reqUser.userId"
    }
  }
])

步骤说明

  • $match:先过滤出符合条件的req文档,减少后续处理的数据量。
  • $lookup:关联reqUser集合,将匹配的文档存入reqUser数组字段。
  • $unwind:将reqUser数组展开为单个文档,直接访问数组内的userId属性。
  • $project:定义最终输出字段,保留reqId、status,提取reqUser.userId,同时排除默认的_id字段(若需要可保留)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:35:22