I'd like to retrieve a mongo selector for the latest posts for each of the catagory ids I specify.
Here is an example of objects in the forumTopics collection:
{
_id: ...,
createdTime: [unix epoch timestamp],
catagory: "someid"
}
In my code, I have an array of the category IDs I would like:
catagories = ["someid", "someotherid"]
I can fetch the posts for the catagories like this:
forumTopics.find {catagory: {$in: catids}}
My question is how I can fetch just one topic object for each category, the one fetched object being the one with the greatest createdTime. I know how to fetch with a limit of 1, but I'm not sure how to get one for each category in the $in.
You can do this by using the aggregation framework:
forumTopics.aggregate( [
{ $match: { catagory: {$in: catids} } },
{ $sort: { createdTime: 1 } },
{ $group: {
_id: "$catagory",
forumTopicId: {
$last: "$_id"
}
}
}
] )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With