Get 10 objects within each category from a collection with MongoDB

Viewed 93

I am trying to retrieve a total of 50 objects from a collection with mongoose.

But I don't want just the 50 most recent, but instead 10 objects within each category.

Each object has a field category with string values. I could, for instance, do 5 different requests and combine them when I'm done.

So it would be something like

Post.find({ category: 'A' }.limit(10).then(posts_a => {
  Post.find({ category: 'B' }.limit(10).then(posts_b => {
    Post.find({ category: 'C' }.limit(10).then(posts_c => {
      Post.find({ category: 'D' }.limit(10).then(posts_d => {
        Post.find({ category: 'E' }.limit(10).then(posts_e => {
          return posts_a.concat(posts_b).concat(posts_c).concat(posts_d).concat(posts_e);
        });
      });
    });
  });
});

but it seems to be very ineffective to make 5 requests. Would it be possible to accomplish the same with only 1 request?

0 Answers
Related