Manoj M J
Manoj M J

Reputation: 449

where().first vs find_by on mongoid

Newbie to rails with mongoid.

Is there any performance impact difference between using

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

and

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

I see in console that both these queries use "Limit 1" in query (when I used on Postgres). Is it the same behavior in Mongoid?

Upvotes: 0

Views: 1474

Answers (2)

Ursus
Ursus

Reputation: 30056

It seems find_by uses where and first internally

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

Upvotes: 3

YaEvan
YaEvan

Reputation: 720

The comments above have explained the internals. I saw a comparison on performance. This is the github code and the result link. Performance Comparison

enter image description here

Upvotes: 0

Related Questions