where()。在mongoid上的第一个vs find_by

问题描述 投票:0回答:2

新手与mongoid轨道。

使用之间是否存在任何性能影响差异

Model.where(:name => "XYZ").first

Model.find_by(:name => "XYZ")

我在控制台中看到这两个查询在查询中使用“限制1”(当我在Postgres上使用时)。在Mongoid中是否有相同的行为?

ruby-on-rails ruby mongoid
2个回答
3
投票

似乎find_by内部使用wherefirst

def find_by(attrs = {})
  result = where(attrs).find_first
  if result.nil? && Mongoid.raise_not_found_error
    raise(Errors::DocumentNotFound.new(self, attrs))
  end
  yield(result) if result && block_given?
  result
end

0
投票

上面的评论解释了内部结构。我看到了性能的比较。这是github代码和结果链接。 Performance Comparison

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.