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

MongoDB双嵌套数组如何实现聚合查询与lookup关联操作

MongoDB多集合关联聚合查询解决方案

以下是可直接运行的完整聚合脚本,完全适配你要求的返回格式:

db.issue.aggregate([
  // 展开data数组,将每个分类项拆分为独立文档方便后续关联
  { $unwind: "$data" },
  // 关联category集合获取分类名称
  {
    $lookup: {
      from: "category",
      localField: "data.categoryId",
      foreignField: "_id",
      as: "categoryInfo"
    }
  },
  // 拆分分类关联结果(单条匹配场景直接提取对象)
  { $unwind: "$categoryInfo" },
  // 关联article集合获取对应分类下的所有文章详情
  {
    $lookup: {
      from: "article",
      localField: "data.articles",
      foreignField: "_id",
      as: "articleList"
    }
  },
  // 格式化文章字段,将_id转为字符串并重命名
  {
    $addFields: {
      "articleList": {
        $map: {
          input: "$articleList",
          as: "item",
          in: {
            id: { $toString: "$$item._id" },
            title: "$$item.title",
            url: "$$item.url"
          }
        }
      }
    }
  },
  // 按issue的_id分组,重新组装data数组
  {
    $group: {
      _id: "$_id",
      // 注意:你期望结果中的tittle为拼写错误,如需正确字段可改键名为title
      tittle: { $first: "$title" },
      data: {
        $push: {
          categoryId: { $toString: "$data.categoryId" },
          categoryName: "$categoryInfo.name",
          articles: "$articleList"
        }
      }
    }
  },
  // 格式化最外层返回字段
  {
    $project: {
      _id: 0,
      id: { $toString: "$_id" },
      tittle: 1,
      data: 1
    }
  }
])

注意事项

  • 如果需要查询指定issue,可在聚合最开头添加$match阶段筛选,示例:{ $match: { _id: ObjectId("612775fbd237d9769a9fc3e4") } }
  • 脚本默认将所有ObjectId转为字符串返回,完全匹配你给出的结果格式要求
  • 如果你期望返回的最外层标题字段是正确拼写的title,修改$group阶段的tittle键名为title即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:24:01