在 MongoDB 中获取包含 n 个最新评论的帖子

Get posts with n latest comments in MongoDB

所以这是一个常见的问题,得到 post 的评论,我似乎无法在 MongoDB 中解决,不像 MySQL 中可以用 left-join.

问题:

我想获取 最新的 8 posts,每个 post 有 2 个最近的评论在 MongoDB

数据:

Post:
{ body: "post1" }
{ body: "post2" }
{ body: "post3" }
...
{ body: "post8" }

Comment:
{ post_id: 1, message: "comment1" }
{ post_id: 2, message: "comment2" }
{ post_id: 2, message: "comment3" }
{ post_id: 3, message: "comment4" }

所有文档都有一个 date 字段,但由于简洁而被删除

预期结果:

{ 
  body:"post1", 
  comments: [
    { post_id: 1, message: "comment1" }
  ]
}
{ 
  body:"post2", 
  comments: [
    { post_id: 2, message: "comment2" },
    { post_id: 2, message: "comment3" }
  ]
}
{ 
  body:"post3", 
  comments: [
    { post_id: 3, message: "comment4" }
  ]
}
...

如果您使用的是 MongoDB 3.6 或更高版本,您可以使用 $lookup with custom pipeline to "join" posts with comments and take 2 most recent ones (using $limit)

db.posts.aggregate([
    {
        $sort: { date: -1 }
    },
    {
        $limit: 8
    },
    {
        $lookup: {
            from: "comments",
            let: { postId: "$_id" },
            pipeline: [
                { $match: { $expr: { $eq: [ "$$postId", "$post_id" ] } } },
                { $sort: { date: -1 } },
                { $limit: 2 }
            ],
            as: "comments"
        }
    }
])