GTDev GTDev - 1 year ago 130
Ruby Question

Mongoid random document

Lets say I have a Collection of users. Is there a way of using mongoid to find n random users in the collection where it does not return the same user twice? For now lets say the user collection looks like this:

class User
include Mongoid::Document
field :name

Simple huh?



The best solution is going to depend on the expected size of the collection.

For tiny collections, just get all of them and .shuffle.slice!

For small sizes of n, you can get away with something like this:

result = (0..User.count-1).sort_by{rand}.slice(0, n).collect! do |i| User.skip(i).first end

For large sizes of n, I would recommend creating a "random" column to sort by. See here for details: