假设我有一个用户集合。有没有一种方法可以使用 mongoid 在集合中查找 n 个随机用户,而不会两次返回同一用户?现在假设用户集合如下所示:
class User
include Mongoid::Document
field :name
end
很简单吧?
谢谢
最佳答案
如果你只想要一个文档,不想定义一个新的标准方法,你可以这样做:
random_model = Model.skip(rand(Model.count)).first
如果您想根据某些标准找到一个随机模型:
criteria = Model.scoped_whatever.where(conditions) # query example
random_model = criteria.skip(rand(criteria.count)).first
关于ruby-on-rails - Mongoid 随机文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7759250/