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

如何通过MongoDB聚合将嵌套数组ID替换为关联文档数据

MongoDB聚合查询:替换contentSource数组中的contentId字段

问题说明

现有聚合查询需将contentSource数组内每个元素的contentId字段,替换为contentsources集合中对应的businessName、thumbnail、status字段数据,同时避免因使用unwind导致文档拆分。

修改后的聚合查询代码

[
  { $match: { _id: mongoose.Types.ObjectId(id) } },
  // 保留原有关联查询
  { $lookup: { from: "cat", localField: "cat", foreignField: "_id", as: "childs", pipeline: [{ $project: { _id: 1, catName: 1, patName: 1 } }] } },
  { $lookup: { from: "patName", localField: "pat", foreignField: "_id", as: "parents", pipeline: [{ $project: { _id: 1, patName: 1, status: 1, thumbnail: 1, desc: 1 } }] } },
  { $lookup: { from: "cha", localField: "cha", foreignField: "_id", as: "cha", pipeline: [{ $project: { _id: 1, chan: 1, cha: 1, status: 1 } }] } },
  { 
    $lookup: { 
      from: "users", 
      localField: "user", 
      foreignField: "_id", 
      as: "users",
      pipeline: [
        { $lookup: { from: "roles", localField: "role", foreignField: "_id", as: "userroles" } },
        { $project: { _id: 1, fullName: 1, profileName: 1, email: 1, icon: 1, status: 1, urerRole: { $first: "$userroles.name" }, position: 1 } }
      ]
    } 
  },
  // 获取contentsources关联数据
  { 
    $lookup: { 
      from: "contentsources", 
      localField: "contentSource.contentId", 
      foreignField: "_id", 
      as: "contentsources",
      pipeline: [{ $project: { _id: 1, businessName: 1, thumbnail: 1, status: 1 } }]
    }
  },
  // 处理contentSource数组,替换contentId
  {
    $project: {
      tribeLogo: 1,
      name: 1,
      type: 1,
      desc: 1,
      createdDate: 1,
      parents: 1,
      childs: 1,
      rsschannels: 1,
      users: 1,
      status: 1,
      contentSource: {
        $map: {
          input: "$contentSource",
          as: "item",
          in: {
            upVote: "$$item.upVote",
            downVote: "$$item.downVote",
            totalVote: "$$item.totalVote",
            syndicateScore: "$$item.syndicateScore",
            contentId: {
              $first: {
                $filter: {
                  input: "$contentsources",
                  cond: { $eq: ["$$this._id", "$$item.contentId"] }
                }
              }
            }
          }
        }
      }
    }
  }
]

核心逻辑

  • 用$map遍历contentSource数组,逐个处理元素
  • 通过$filter从contentsources数组中匹配对应_id的文档,$first确保只取唯一匹配结果
  • 直接在$project阶段完成数组结构转换,无需unwind和group操作,避免文档拆分

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 15:02:07