MongoDB:返回子文档中仅存在于父文档中的字段?

问题描述 投票:0回答:1

我有这个

Mongo DB
查询以我期望的格式返回:

db.getCollection("myCollection").aggregate([
  {
    $lookup: {
      from: "myCollection",
      localField: "parent_id",
      foreignField: "parent_id",
      as: "children"
    }
  },
  { $unwind: "$children" },
  { $replaceWith: "$children" }
])

但是,我也希望

parent_desc
字段仅出现在父文档中在我的响应中的子文档中返回

示例子文档:

{
id: doc_123_2
parent_id: 123
active: true
}

示例父文档:

{
_id: doc_123
parent_id: 123
active: true
parent_desc: sample parent desc
}

如何修改我的查询来执行此操作?

json mongodb nosql bson cosmos
1个回答
0
投票

首先过滤掉父母,因为不需要从孩子那里查找
查找内部可以有管道来检查相等的父 ID 并添加您需要的额外描述字段
剩下的就是你已经完成的事情

db.myCollection.aggregate([
  { $match: { parent_desc: { $exists: true } } },
  {
    $lookup: {
      from: "myCollection",
      let: { parentId: "$parent_id", parentDesc: "$parent_desc" },
      pipeline: [
        { $match: { $expr: { $eq: [ "$$parentId", "$parent_id" ] } } },
        { $addFields: { parent_desc: "$$parentDesc" } }
      ],
      as: "children"
    }
  },
  { $unwind: "$children" },
  { $replaceWith: "$children" }
])

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.