Skip to content

Instantly share code, notes, and snippets.

@ccorcos
Created April 21, 2014 01:13
Show Gist options
  • Save ccorcos/11129592 to your computer and use it in GitHub Desktop.
Save ccorcos/11129592 to your computer and use it in GitHub Desktop.
get a random document from a collection (meteor, mongodb)
randomInRange = function(min, max) {
var random = Math.floor(Math.random() * (max - min + 1)) + min;
return random;
}
randomFromCollection = function(C) {
return function() {
c = C.find().fetch();
i = randomInRange(0, c.count())
return c[i]
}
}
@si4dev
Copy link

si4dev commented Nov 27, 2015

You might want to use Random.choice(arrayOrString) which is already included as part meteor. From the Meteor docs http://docs.meteor.com/#random

@kamiel79
Copy link

Using findone appears a lot more efficient, you could just feed the random number (which you calculate with randomInRange(0,collection.count()) into the skip argument
http://docs.meteor.com/#/full/findone

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment