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

如何在MongoDB Compass聚合中提取嵌套字段并重组文档

MongoDB聚合生成指定结构文档的可行方案

根据你的需求,以下分两种常见的数据模型场景给出具体的聚合实现方案:

场景1:原始嵌套结构(单集合)

如果你的数据是单集合嵌套数组结构,示例文档如下:

{
  "_id": ObjectId("60d21b4667d0d8992e610c85"),
  "Plan": [{"Name": "基础会员套餐"}, {"Name": "年度VIP套餐"}],
  "User": [{"FirstName": "王", "LastName": "明"}, {"FirstName": "赵", "LastName": "亮"}]
}

需求1:展开数组生成多组关联文档

如果需要将每个Plan和User的组合生成独立文档,使用以下聚合管道:

db.yourCollection.aggregate([
  // 展开Plan数组,每个元素生成单独文档
  { $unwind: "$Plan" },
  // 展开User数组,每个元素生成单独文档
  { $unwind: "$User" },
  // 提取并拼接目标字段
  {
    $project: {
      _id: 1,
      PlanName: "$Plan.Name",
      UserName: { $concat: ["$User.FirstName", " ", "$User.LastName"] }
    }
  }
])

需求2:仅取数组首个元素生成单文档

如果只需要每个原始文档对应一组Plan和User(取数组第一个元素),无需展开数组:

db.yourCollection.aggregate([
  {
    $project: {
      _id: 1,
      // 提取Plan数组第一个元素的Name
      PlanName: { $arrayElemAt: ["$Plan.Name", 0] },
      // 拼接User数组第一个元素的姓名
      UserName: {
        $concat: [
          { $arrayElemAt: ["$User.FirstName", 0] },
          " ",
          { $arrayElemAt: ["$User.LastName", 0] }
        ]
      }
    }
  }
])

场景2:拆分后的多集合结构(已优化模型)

如果已经将Plan和User拆分为独立集合(比如main主集合、plans套餐集合、users用户集合),示例结构如下:

  • main集合:{ "_id": ObjectId("60d21b4667d0d8992e610c85"), "planId": ObjectId("60d21b8967d0d8992e610c86"), "userId": ObjectId("60d21bc067d0d8992e610c87") }
  • plans集合:{ "_id": ObjectId("60d21b8967d0d8992e610c86"), "Name": "基础会员套餐" }
  • users集合:{ "_id": ObjectId("60d21bc067d0d8992e610c87"), "FirstName": "王", "LastName": "明" }

使用$lookup关联后生成目标结构的聚合管道:

db.main.aggregate([
  // 关联plans集合获取套餐名称
  {
    $lookup: {
      from: "plans",
      localField: "planId",
      foreignField: "_id",
      as: "Plan"
    }
  },
  // 关联users集合获取用户信息
  {
    $lookup: {
      from: "users",
      localField: "userId",
      foreignField: "_id",
      as: "User"
    }
  },
  // 将关联后的数组转为单个对象(一对一关联场景)
  { $unwind: "$Plan" },
  { $unwind: "$User" },
  // 生成最终目标字段
  {
    $project: {
      _id: 1,
      PlanName: "$Plan.Name",
      UserName: { $concat: ["$User.FirstName", " ", "$User.LastName"] }
    }
  }
])

如果是一对多关联(比如主集合包含planIds数组),只需在$lookup后添加$unwind展开关联数组即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:05:22