Method: Mongoid::Criteria::Queryable::Optional#order_by

Defined in:
lib/mongoid/criteria/queryable/optional.rb

#order_by(*spec) ⇒ Optional Also known as: order

Adds sorting criterion to the options.

Examples:

Add sorting options via a hash with integer directions.

optional.order_by(name: 1, dob: -1)

Add sorting options via a hash with symbol directions.

optional.order_by(name: :asc, dob: :desc)

Add sorting options via a hash with string directions.

optional.order_by(name: "asc", dob: "desc")

Add sorting options via an array with integer directions.

optional.order_by([[ name, 1 ], [ dob, -1 ]])

Add sorting options via an array with symbol directions.

optional.order_by([[ :name, :asc ], [ :dob, :desc ]])

Add sorting options via an array with string directions.

optional.order_by([[ "name", "asc" ], [ "dob", "desc" ]])

Add sorting options with keys.

optional.order_by(:name.asc, :dob.desc)

Add sorting options via a string.

optional.order_by("name ASC, dob DESC")

Parameters:

  • *spec ([ Array | Hash | String ]...)

    The sorting specification.

Returns:



170
171
172
173
174
175
176
177
178
179
# File 'lib/mongoid/criteria/queryable/optional.rb', line 170

def order_by(*spec)
  option(spec) do |options, query|
    spec.compact.each do |criterion|
      criterion.__sort_option__.each_pair do |field, direction|
        add_sort_option(options, field, direction)
      end
      query.pipeline.push("$sort" => options[:sort]) if aggregating?
    end
  end
end