Matteo Pagliazzi
Matteo Pagliazzi

Reputation: 5260

Mongoid where vs find when using id as criteria

when using document's id as the only criteria in my query what's the difference between:

Board.only(:_id).find(params[:board_id])

and

Board.where(_id: params[:board_id]).only(:_id)

the only thing i've noticed is that printing the result as json when using where it encloses the result in square brackets

Upvotes: 6

Views: 7661

Answers (3)

Petr Bela
Petr Bela

Reputation: 8741

The previous answers are correct, I'll just add that to find one record without raising an error, the equivalent to find is where.first. In your case

Board.where(_id: params[:board_id]).first.only(:_id)

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

To add to Kyle's answer:

If matching record is not found: find throws exception, where returns empty enumerable.

Upvotes: 4

Kyle
Kyle

Reputation: 22258

find returns one document.

where returns an array of documents that match the criteria.

Upvotes: 11

Related Questions