ruby-on-rails – Mongoid随机文件
发布时间:2020-12-16 22:21:55 所属栏目:百科 来源:网络整理
导读:让我说我有一个用户的集合.有没有办法使用mongoid在集合中找到n个不再返回相同用户的n个随机用户?现在让我们说用户集合如下所示: class User include Mongoid::Document field :nameend 简单啊 谢谢 解决方法 最好的解决方案将取决于集合的预期大小. 对于
让我说我有一个用户的集合.有没有办法使用mongoid在集合中找到n个不再返回相同用户的n个随机用户?现在让我们说用户集合如下所示:
class User include Mongoid::Document field :name end 简单啊 谢谢 解决方法
最好的解决方案将取决于集合的预期大小.
对于小集合,只需要得到所有的和.shuffle.slice! 对于小尺寸的n,你可以得到这样的东西: result = (0..User.count-1).sort_by{rand}.slice(0,n).collect! do |i| User.skip(i).first end 对于大尺寸的n,我建议创建一个“随机”列进行排序.详情请见:http://cookbook.mongodb.org/patterns/random-attribute/ https://github.com/mongodb/cookbook/blob/master/content/patterns/random-attribute.txt (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |