所以我需要返回一个主题集合,每个主题都有一个“mostRecentThree”属性,其中包含 3 个最新帖子
我有 2 个收藏
话题
{name:'food', foo:bar}
邮政
{ topic:'food', created: someDate }
返回结果应该是设置了 recentThree 属性的集合
{name:food, recentThree: [postId1, postId2, postId3], foo:bar}
这样做最有效的方法是什么?
我这么晚才回答,这对其他人有帮助,
将aggregate()与管道一起使用,
post收藏$match topic和name表达式使用$exprand$eq$sort按日期降序(-1)顺序,表示最新的将在前$limit获取已在上述管道中排序的前 3 条记录db.topic.aggregate([
{
$lookup: {
from: "post",
as: "recentThree",
let: { name: "$name" },
pipeline: [
{
$match: {
$expr: { $eq: ["$topic", "$$name"] }
}
},
{ $sort: { created: -1 } },
{ $limit: 3 }
]
}
}
])