我无法使用Array#shuffle
因为我没有获取所有文件(我最多只能获取20个文档)。如何使用MongoMapper从MongoDB数据库中获取随机文档(即在MySQL中使用ORDER BY RAND()
)?
答案 0 :(得分:3)
没有类似于ORDER BY RAND()
的技术。甚至在MySQL中也建议避免使用它(在大型表格上)。
然而,你可以应用一些常见的技巧。
例如,如果您知道id的最小值和最大值,则选择范围内的随机值并获取下一个对象。
db.collection.find({_id: {$gte: random_id}}).limit(1);
重复20次。
或者您可以自己为每个文档添加“随机”字段(并且每隔一段时间重新调整一次)。这样,每次查询都不会得到真正随机的结果,但它会相当便宜。
db.collection.find().sort({pseudo_random_field: 1}).limit(20)
// you can also skip some records here, but don't skip a lot.
答案 1 :(得分:0)
使用skip和Random类。
class Book {
include MongoMapper::Document
key :title
key :author
}
rand = Random.rand(0..(Book.count-1))
Book.skip(rand).first