我想检索一个mongo选择器,以获取我指定的每个类别id的最新帖子。
以下是forumTopics
集合中对象的示例:
{
_id: ...,
createdTime: [unix epoch timestamp],
catagory: "someid"
}
在我的代码中,我有一个我想要的类别ID数组:
catagories = ["someid", "someotherid"]
我可以像这样获取catagories的帖子:
forumTopics.find {catagory: {$in: catids}}
我的问题是我如何只为每个类别获取一个主题对象,一个获取的对象是具有最大createdTime
的对象。我知道如何获取限制为1,但我不确定如何为$in
中的每个类别获取一个。
答案 0 :(得分:3)
您可以使用聚合框架执行此操作:
forumTopics.aggregate( [
{ $match: { catagory: {$in: catids} } },
{ $sort: { createdTime: 1 } },
{ $group: {
_id: "$catagory",
forumTopicId: {
$last: "$_id"
}
}
}
] )