MongoDB每个一个

MongoDB每个一个,mongodb,meteor,Mongodb,Meteor,我想为我指定的每个分类ID的最新文章检索一个mongo选择器 以下是forumTopics集合中的对象示例: { _id: ..., createdTime: [unix epoch timestamp], catagory: "someid" } 在我的代码中,我有一个我想要的类别ID数组: categories=[“someid”,“someotherid”] 我可以为以下类别获取帖子: forumTopics.find{catagory:{$in:catids}}

我想为我指定的每个分类ID的最新文章检索一个mongo选择器

以下是
forumTopics
集合中的对象示例:

{
    _id: ...,
    createdTime: [unix epoch timestamp],
    catagory: "someid"
}
在我的代码中,我有一个我想要的类别ID数组:

categories=[“someid”,“someotherid”]

我可以为以下类别获取帖子:

forumTopics.find{catagory:{$in:catids}}


我的问题是如何为每个类别只获取一个主题对象,其中一个获取的对象具有最大的
createdTime
。我知道如何在限制为1的情况下获取,但我不确定如何为
$in

中的每个类别获取一个。您可以使用聚合框架:

forumTopics.aggregate( [
    { $match: { catagory: {$in: catids} } },
    { $sort: { createdTime: 1 } },
    { $group: {
            _id: "$catagory",
            forumTopicId: {
                $last: "$_id"
            }
        }
    }
] )

再补充一句,这个包是关于大气的:啊,传说中的MapReduce。。。令人惊叹的。