Mongoid随机文件 [英] Mongoid random document

查看:54
本文介绍了Mongoid随机文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个用户集合.有没有一种方法可以使用Mongoid在集合中找到n个随机用户,而不会两次返回同一用户?现在,可以说用户集合如下所示:

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

简单吧?

谢谢

推荐答案

最好的解决方案将取决于集合的预期大小.

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

对于微小的收藏,只需将它们全部收集并.shuffle.slice即可!

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

对于n的小尺寸,您可以避免出现以下情况:

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

对于大尺寸的n,我建议创建一个随机"列进行排序.详情请参阅此处: http://cookbook.mongodb.org/patterns/random -attribute/ https ://github.com/mongodb/cookbook/blob/master/content/patterns/random-attribute.txt

For large sizes of n, I would recommend creating a "random" column to sort by. See here for details: http://cookbook.mongodb.org/patterns/random-attribute/ https://github.com/mongodb/cookbook/blob/master/content/patterns/random-attribute.txt

这篇关于Mongoid随机文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆