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
javascript node.js mongodb mongoose


source to share


No one has answered this question yet

See similar questions:

fourteen
Mongodb $ group group aggregation, limit array length

or similar:

5722
How can I remove a property from a JavaScript object?
2132
Get selected text from dropdown (select field) using jQuery
1262
What is the best way to add options to select from a JS object using jQuery?
1209
How to get value from GET parameters?
1068
How can I remove a key from a JavaScript object?
873
Big data workflows using pandas
825
How to delete MongoDB database from command line?
758
How can I get the complete object in Node.js console.log () and not in [Object]?
0
MongoDB joins collections or has multiple links
0
Display cursor and for each not working, mongodb & mongoose



All Articles
Loading...
X
Show
Funny
Dev
Pics