Search code examples
mongoid3

Best strategy for picking random documents in Mongoid


I need to pick a random document out of my database and wanted to know a better strategy than the Ruby shuffle method that is less resource intensive for large databases.


Solution

  • Add a "random" field and have the default value set by a proc that returns a random float. Whenever you need to pull a random document, just type Model.where(:random.gt => rand).first