因此,这是一个常见的问题,有评论的帖子,我似乎不能在MongoDB中解决,不像在MySQL中,后者很容易用left-join解决。
问题:
我想获取最新的8篇文章和2最近的评论在MongoDB中的每一篇文章
postSchema.virtual('comments', ..),然后在执行查询时使用Post.find(..).populate('comments', options: {limit: 2})填充,但不幸的是限制返回不一致结果。数据:
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" }
]
}
...发布于 2018-11-09 22:18:29
如果您使用的是MongoDB 3.6或更高版本,您可以使用带有自定义管道的$lookup与注释“联接”帖子,并使用2个最近的帖子(使用$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"
}
}
])https://stackoverflow.com/questions/53233771
复制相似问题