Ruby on rails mongoid作用域链上的Execute方法

Ruby on rails mongoid作用域链上的Execute方法,ruby-on-rails,activerecord,model,mongoid,Ruby On Rails,Activerecord,Model,Mongoid,我需要使用Rails和MongoId随机获取一些文档。因为我计划有非常大的集合,所以我决定在每个文档中放置一个“随机”字段,并使用该字段选择文档。我在模型中编写了以下方法: def random(qty) if count <= qty all else collection = [ ] while collection.size < qty collection << where(:random_field.gt =>

我需要使用Rails和MongoId随机获取一些文档。因为我计划有非常大的集合,所以我决定在每个文档中放置一个“随机”字段,并使用该字段选择文档。我在模型中编写了以下方法:

def random(qty)
  if count <= qty
    all
  else
    collection = [ ]
    while collection.size < qty
      collection << where(:random_field.gt => rand).first
    end
    collection
  end
end
我得到:

undefined method `random' for #<Array:0x0000000bf78748>
未定义的方法“random”#
相反,如果我尝试使该方法类似于lambda范围,我会得到:

undefined method `to_criteria' for #<Array:0x0000000df824f8>
未定义的方法“符合标准”#
考虑到我对应用随机范围之后的任何其他范围都不感兴趣,我如何在链中使用我的方法


提前感谢。

我用以下内容扩展了Mongoid::Criteria类。不知道这是不是最好的选择。事实上,我认为它相当慢,因为它至少执行数量查询

我不知道普通ActiveRecord模块是否可以使用not_in。但是,如果需要,您可以部分移除not_。这只是减少查询数量的优化

对于文档数是数量的两倍(或更大)的集合,您应该有确切的数量查询

模块Mongoid
等级标准
def随机(数量)
如果计数rand)。不在(id:ids)中。首先
除非厄尔尼诺?

这是一个有趣的解决方案。在过去,我使用
pull
提取所有id(相对较快),然后
sample(n)
随机抽取id样本。然后
Model.find(id)
取出随机的n个模型。
undefined method `to_criteria' for #<Array:0x0000000df824f8>
module Mongoid
  class Criteria

    def random(qty)
      if count <= qty
        all
      else
        res = [ ]
        ids = [ ]
        while res.size < qty
          el = where(:random_field.gt => rand).not_in(id: ids).first

          unless el.nil?
            res << el
            ids << el._id
          end
        end
        res
      end
    end

  end
end