我有一个帖子ID数组。对帖子的评论是它自己的集合,而不是嵌入的。现在我想在一个查询中理想地检索每个帖子 ID 的最新评论。 post_id
是每个注释文档中的一个字段,当然也是一个timestamp
。
发布:
{
_id: 123
}
评论:
{
_id: 567,
post_id: 123,
timestamp: 1498117182
}
由于评论具有帖子 ID,因此它比我最初的想法简单一些。 首先,你得到PostId数组中的所有注释。 按时间戳(最新优先(对注释进行排序,然后按 postId 分组,并对字段使用第一个值
db.getCollection('comments').aggregate([
{$match: {
post_id: {$in : idArray}
}},
{$sort:{ timestamp : -1 }},
{$group:{
_id : post_id,
timestamp: { $first: "$timestamp" },
comment_id: { $first: "$_id" }
}}
]);