Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
end

Simple huh?

Thanks

like image 901
GTDev Avatar asked Oct 13 '11 19:10

GTDev


People also ask

How do I generate a random document in MongoDB?

You can also use MongoDB's geospatial indexing feature to select the documents 'nearest' to a random number. This requires only one query and no null checks, plus the code is clean, simple and flexible. You could even use the Y-axis of the geopoint to add a second randomness dimension to your query.

How do I search in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.


1 Answers

If you just want one document, and don't want to define a new criteria method, you could just do this:

random_model = Model.skip(rand(Model.count)).first

If you want to find a random model based on some criteria:

criteria = Model.scoped_whatever.where(conditions) # query example
random_model = criteria.skip(rand(criteria.count)).first
like image 125
tothemario Avatar answered Oct 03 '22 03:10

tothemario