所以我需要返回一个主题集合,每个主题都有一个“mostRecentThree”属性设置在3个最新帖子上
我有2个收藏品
主题
{name:'food', foo:bar}
发布
{ topic:'food', created: someDate }
返回结果应该是具有recentThree属性集
的集合{name:food, recentThree: [postId1, postId2, postId3], foo:bar}
最有效的方法是什么?
答案 0 :(得分:0)
我来晚了,这将对其他人有帮助,
将aggregate()与管道一起使用
post
集合$match
topic
和name
表达式,使用$expr
和$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 }
]
}
}
])