I’d like to show random users on the home-page of my app, together with an end-less scrolling mechanism. Before Meteor was on MongoDB 3.2, I used some pretty weird code to do this, but with MongoDB 3.2, there is a sample() method:
https://docs.mongodb.com/manual/reference/operator/aggregation/sample/
Now I am wondering how I could use this in combination with Meteor’s MongoDB wrappers? The API only supports skip
and limit
, but not sample
. Is there a way to workaround this limitation by accessing the underlying Mongo collection code? I only need this on server-side, inside a Meteor method.
Exactly that. However, this is an aggregation pipeline stage, so it’s a little more complex than a straight collection query.
Meteor.methods({
async getRandomDocs(n) {
// return array of n random docs
return await someCollection.rawCollection().aggregate([ { $sample: { size: n} } ]).toArray();
},
});
I just hacked that in here, so it’s untested!
2 Likes
Hey, thanks a lot for your fast reply. Highly appreciated, as always!
Wonder if that also works in combination with a cursor, i.e. skip and limit? This would help implementing endless scrolling with delayed loading. I’ll try it.
BTW: Didn’t know yet that you can use async/await in this context. Pretty cool.