查找后在对象数组中设置字段。蒙古数据库

Lou*_*ous 2 mongodb node.js mongodb-query aggregation-framework

我有两个收藏usersposts

用户有这样的文档:

{
  _id: ObjectId('611142303c409b5dc826e563'),
  name: 'foo'
}
Run Code Online (Sandbox Code Playgroud)

posts有这样的文档:

{
  _id: ObjectId('611142303c409b5dc826e111'),
  comments:[
    {
      owner: ObjectId('611142303c409b5dc826e563'),
      description: "my description"
    },
    {
      owner: ObjectId('611142303c409b5dc826e333'),
      description: "my description2"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

当我收到服务器端的请求时,我需要返回所有者的整个文档,而不仅仅是其 id。

例如对于一个 get 请求我必须返回:

{
  _id: ObjectId('611142303c409b5dc826e111'),
  comments:[
    {
      owner:{
        _id: ObjectId('611142303c409b5dc826e563'),
        name: 'foo'
    },
      description: "my description"
    },
    {
      owner:     {
        _id: ObjectId('611142303c409b5dc826e555'),
        name: 'foo2'
      },
      description: "my description2"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

为此,我执行了以下管道:

[
  $lookup:{
    from: 'owners',
    localField: 'comments.owner',
    foreignField: '_id',
    as: 'owners_comments'
  }
]
Run Code Online (Sandbox Code Playgroud)

通过这种方式,我得到了一组在一个特定文档中发表评论的所有者。

我的问题是如何为每条评论获取正确的所有者资料?我知道我可以更轻松地在服务器端进行操作,但我更喜欢在数据库端进行。

我想映射每个评论并在内部过滤owners_comments,但在 mongo 聚合中我遇到了一些问题。

您有什么建议吗?

Tom*_*ert 5

您必须对$unwind注释数组进行操作,然后执行$lookup然后才能$group恢复原始结构,如下所示:

db.posts.aggregate([
  {
    $unwind: "$comments"
  },
  {
    $lookup: {
      from: "owners",
      localField: "comments.owner",
      foreignField: "_id",
      as: "owners"
    }
  },
  {
    $group: {
      _id: "$_id",
      comments: {
        $push: {
          owner: "$comments.owner",
          description: "$comments.description",
          owner_profile: {
            "$arrayElemAt": [
              "$owners",
              0
            ]
          },
          
        }
      }
    }
  }
])
Run Code Online (Sandbox Code Playgroud)

蒙戈游乐场