我有这个Mongo DB查询,它以我期望的格式返回:

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

然而,我还希望在我的响应中在子文档中返回为only present in the parent docsparent_desc字段

example child doc:

{
id: doc_123_2
parent_id: 123
active: true
}

example parent doc:

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

如何修改我的查询来做到这一点?

推荐答案

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

要将父文档中存在的字段返回到子文档,您可以遵循以下代码.它使用addFields将所需字段parent_desc添加到子文档中,如下面的输出所示:

db.getCollection("newcoll").aggregate([
  {
    $lookup: {
      from: "newcoll",
      localField: "parent_id",
      foreignField: "parent_id",
      as: "children"
    }
  },
  { $unwind: "$children" },
  { $replaceWith: "$children" },
  {
    $lookup: {
      from: "newcoll",
      localField: "parent_id",
      foreignField: "parent_id",
      as: "parent"
    }
  },
  { $unwind: "$parent" },
  {
    $addFields: {
      parent_desc: "$parent.parent_desc"
    }
  },
  {
    $group: {
      _id: "$_id",
      id: { $first: "$id" },
      parent_id: { $first: "$parent_id" },
      active: { $first: "$active" },
      parent_desc: { $first: "$parent_desc" }
    }
  },
  {
    $project: {
      _id: 1,
      id: 1,
      parent_id: 1,
      active: 1,
      parent_desc: 1
    }
  }
]).pretty()

Output:

{
        "_id" : ObjectId("662616f0af88e119ac2f49c3"),
        "id" : "doc_123_2",
        "parent_id" : "123",
        "active" : true,
        "parent_desc" : "sample parent desc"
}
{
        "_id" : ObjectId("66261744af88e119ac2f49c4"),
        "id" : "doc_123",
        "parent_id" : "123",
        "active" : true,
        "parent_desc" : "sample parent desc"
}

Mongodb相关问答推荐

用其他集合中的文档替换嵌套文档数组中的值

MongoDB - 将对象转换为数组

如何匹配 MongoDB 中同一文档中两个字段的比较?

根据聚合管道MongoDB Atlas触发器中的条件更新多个字段

MongoDB - 在 $lookup 管道中匹配键匹配不起作用

mongoose中的 required是什么意思?

为什么使用整数作为 pymongo 的键不起作用?

如何将 json 字符串编组到 bson 文档以写入 MongoDB?

.insertOne 不是函数

如何将查询结果(单个文档)存储到变量中?

将MongoDB连接到前端?

带有 mongodb 和 nodejs 的实时 Web 应用程序

pymongo 排序和 find_one 问题

删除嵌套文档数组中的嵌入文档

Select 匹配mongodb中两个字段的concat值的记录

使用 brew upgrade Mongo update from 3.4 to 4.0 报错:在try 升级到 4.0 之前,数据文件需要完全升级到 3.6 版

如何使用 MongoDB 以编程方式预拆分基于 GUID 的分片键

MongoDB InsertMany 与 BulkWrite

我需要手动关闭mongoose连接吗?

Mongodb Compass 无法在 Ubuntu 18.10 中打开