0

Let's say I have a list of items. I need to find (return a cursor) exactly 8 items. First I need to see how many featured items are there. If I can get 8 featured items, then no issue. But if the count is less than 8, I need to randomly items until I get 8.

Is it possible to do this in mongodb?

THpubs
  • 7,804
  • 16
  • 68
  • 143
  • It is unclear what you are asking here. Please consider to improve your question and show us sample document with the expected result. – styvane Oct 31 '16 at 08:18

2 Answers2

0

I think what you want to do is pad out the list of items to make sure you always return 8. You can do this in the helper method,

var rows = MyTable.find({search: "Something"}).limit(8).fetch();
for (var i=rows.length;i<8;i++) {
    rows.push({name: "Empty data row "+i}):
}
return rows;
Mikkel
  • 7,693
  • 3
  • 17
  • 31
0

If you sort the cursor by your featured field you can pick up the featured ones first and then fill in with others:

const noMoreThan8Docs = MyCollection.find({},{ sort: { featured: -1 }, limit: 8 });

This assumes that featured is a boolean key. Booleans sort false-then-true so you need to reverse the sort.

I'm not sure how random the documents that are selected after the featured ones will be. However, since you're using Meteor and Meteor uses random _ids (unlike MongoDB native) you can sort on that key as well.

const noMoreThan8Docs = MyCollection.find({},{ sort: { featured: -1, _id: 1 }, limit: 8 });

This is also not truly random since the same non-featured documents will tend to sort first. If you want to really randomize the non-featured items you'll want to do a random find of those and append them if you have less than 8 featured documents.

Community
  • 1
  • 1
Michel Floyd
  • 18,793
  • 4
  • 24
  • 39