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

如何修改MongoDB聚合查询,在子文档中返回父文档独有的parent_desc字段

修改MongoDB聚合查询,在子文档中添加父文档的parent_desc字段

方法一:基于原查询调整(保留原查询逻辑基础)

db.getCollection("myCollection").aggregate([
  {
    $lookup: {
      from: "myCollection",
      localField: "parent_id",
      foreignField: "parent_id",
      as: "children"
    }
  },
  { $unwind: "$children" },
  // 过滤掉父文档本身,只保留子文档(依据示例中父文档_id与子文档id的差异判断)
  { $match: { $expr: { $ne: ["$_id", "$children.id"] } } },
  // 将父文档的parent_desc合并到子文档中
  {
    $replaceWith: {
      $mergeObjects: ["$children", { parent_desc: "$parent_desc" }]
    }
  }
])

逻辑说明:

  1. 原查询通过$lookup拉取了所有同parent_id的文档作为children,但结果会包含父文档本身,因此新增$match阶段过滤掉父文档。
  2. 使用$mergeObjects将父文档的parent_desc字段合并到子文档结构中,再通过$replaceWith返回最终的子文档格式。

方法二:更高效的定向关联(先筛选子文档再关联父文档)

db.getCollection("myCollection").aggregate([
  // 先筛选出子文档(利用parent_desc仅存在于父文档的特性)
  { $match: { parent_desc: { $exists: false } } },
  {
    $lookup: {
      from: "myCollection",
      localField: "parent_id",
      foreignField: "parent_id",
      as: "parent_info",
      // 仅关联存在parent_desc的父文档,且只提取需要的字段
      pipeline: [
        { $match: { parent_desc: { $exists: true } } },
        { $project: { parent_desc: 1, _id: 0 } }
      ]
    }
  },
  { $unwind: "$parent_info" },
  // 合并子文档与父文档的parent_desc字段
  { $replaceWith: { $mergeObjects: ["$$ROOT", "$parent_info"] } },
  { $project: { parent_info: 0 } } // 清理临时关联字段
])

逻辑说明:

  1. 先通过$match过滤出所有子文档,减少后续关联的数据处理量。
  2. 在$lookup中通过子管道精准匹配父文档,只提取需要的parent_desc字段,避免冗余数据。
  3. 最后合并字段并清理临时字段,直接得到包含parent_desc的目标子文档结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:30:23