【问题标题】:set field in array of objects after lookup. MongoDb查找后在对象数组中设置字段。蒙古数据库
【发布时间】:2021-11-02 21:05:01
【问题描述】:

我有两个集合usersposts

用户有这样的文件:

{
  _id: ObjectId('611142303c409b5dc826e563'),
  name: 'foo'
}

posts 有这样的文档:

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

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

例如对于我必须返回的获取请求:

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

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

[
  $lookup:{
    from: 'owners',
    localField: 'comments.owner',
    foreignField: '_id',
    as: 'owners_comments'
  }
]

通过这种方式,我得到了一组所有者,这些所有者在一个特定文档中具有 cmets。

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

我想映射每个评论并在内部过滤 owners_comments,但在 mongo 聚合中我对此几乎没有问题。

你有什么建议吗?

【问题讨论】:

    标签: node.js mongodb mongodb-query aggregation-framework


    【解决方案1】:

    你必须$unwind cmets 数组,然后才执行$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
                ]
              },
              
            }
          }
        }
      }
    ])
    

    Mongo Playground

    【讨论】:

    • 小组赛后我只有_id和cmets。我怎样才能让所有其他人都像以前一样?
    • 您可以通过多种方式重组数据,在小组赛中使用$first 等运算符。但如果你有很多字段,this 是支持它们的最通用方式。
    猜你喜欢
    • 2018-11-22
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多