Get 10 objects in each category from a collection with MongoDB

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

But I don't want only the 50 most recent ones, but instead of 10 objects in each category.

Each object has a field category

with string values. I could, for example, make 5 different requests and combine them when 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 very inefficient to make 5 queries. Is it possible to do the same with only 1 request?

+3


source to share





All Articles