Method: Mongoid::Contextual::Mongo#first

Defined in:
lib/mongoid/contextual/mongo.rb

#firstDocument Also known as: one

Note:

Mongoid previously added an _id sort when no sort parameters were provided explicitly by the user. This caused bad performance issues and was not expected, so #first/#last will no longer guarantee order if no sorting parameters are provided. For order guarantees - a sort must be explicitly provided.

Get the first document in the database for the criteria’s selector.

Examples:

Get the first document.

context.first

Returns:

Since:

  • 3.0.0



237
238
239
240
241
242
# File 'lib/mongoid/contextual/mongo.rb', line 237

def first
  return documents.first if cached? && cache_loaded?
  try_cache(:first) do
    with_eager_loading(view.first)
  end
end