Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB One of Each

Tags:

mongodb

meteor

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.

like image 916
Christian Stewart Avatar asked Jan 23 '26 13:01

Christian Stewart


1 Answers

You can do this by using the aggregation framework:

forumTopics.aggregate( [
    { $match: { catagory: {$in: catids} } },
    { $sort: { createdTime: 1 } },
    { $group: {
            _id: "$catagory",
            forumTopicId: {
                $last: "$_id"
            }
        }
    }
] )
like image 157
heinob Avatar answered Jan 26 '26 10:01

heinob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!