4

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?

Jamgreen
  • 10,329
  • 29
  • 113
  • 224
  • I feel like this would be a good use case for [aggregation](https://docs.mongodb.com/manual/aggregation/) as you are trying to (1) group posts by their category but also (2) limit the number of posts per category. (1) is [achievable](https://docs.mongodb.com/manual/reference/operator/aggregation/group/) whereas (2) [might not be](https://stackoverflow.com/questions/24463689/mongodb-aggregation-group-restrict-length-of-array). – Mikey Jul 11 '17 at 14:20

0 Answers0