如何在聚合Mongodb中使用嵌套引用进行查找?

siotufzp  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(117)

我正在使用$lookup aggregate来连接集合,但我面临着一个来自结果的问题。具体来说,我有三个集合,看起来像:

职位:

id: 1,   
     title: 'my title',
     content: 'bla bla bla',
     ...

备注:

post_id: 1,
     user_id: '123',
     content: 'great article!!!',

使用者:

id: '123',
     name: 'Ferb'

我的代码查询后,这篇文章也包含评论:

$lookup: {
            from: 'comments',
            localField: 'id',
            foreignField: 'post_id',
            as: 'comments',
        },

        $project: {
           id: 1,
           title: 1,
           content: 1,
           comments: '$comments'
        }

According to the results i got:

           id: 1,
           title: 'my title',
           content: 'bla bla bla',
           comments: [
              post_id: 1,
              user_id: '123', // needs to $lookup from User model
              content: 'great article!!!',
           ]

但这不是我所期望的,我想在评论列表中$lookup user_id,并嵌套$lookup。我应该怎么做才能得到预期的结果?

9gm1akwq

9gm1akwq1#

就个人而言,我反对嵌套$lookup的想法,因为这可能会降低查询的可读性。
我更喜欢简单的$lookup两次。

db.posts.aggregate([
  {
    "$lookup": {
      "from": "comments",
      "localField": "id",
      "foreignField": "post_id",
      "as": "commentsLookup"
    }
  },
  {
    "$unwind": "$commentsLookup"
  },
  {
    "$lookup": {
      "from": "users",
      "localField": "commentsLookup.user_id",
      "foreignField": "id",
      "as": "commentsLookup.usersLookup"
    }
  },
  {
    "$unwind": "$commentsLookup.usersLookup"
  },
  {
    $group: {
      _id: "$_id",
      title: {
        $first: "$title"
      },
      content: {
        $first: "$content"
      },
      commentsLookup: {
        $push: "$commentsLookup"
      }
    }
  }
])

Mongo Playground
但是,如果你坚持嵌套$lookup,这里有一种方法。

db.posts.aggregate([
  {
    "$lookup": {
      "from": "comments",
      "localField": "id",
      "foreignField": "post_id",
      "pipeline": [
        {
          "$lookup": {
            "from": "users",
            "localField": "user_id",
            "foreignField": "id",
            "as": "usersLookup"
          }
        },
        {
          "$unwind": "$usersLookup"
        }
      ],
      "as": "commentsLookup"
    }
  },
  {
    "$unwind": "$commentsLookup"
  }
])

Mongo Playground

相关问题