Method: Mongoid::Contextual::Mongo#pluck

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

#pluck(*fields) ⇒ Array<Object, Array>

Note:

This method will return the raw db values - it performs no custom serialization.

Pluck the single field values from the database. Will return duplicates if they exist and only works for top level fields.

Examples:

Pluck a field.

context.pluck(:_id)

Parameters:

  • field (String, Symbol, Array)

    Fields to pluck.

Returns:

  • (Array<Object, Array>)

    The plucked values.

Since:

  • 3.1.0



399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/mongoid/contextual/mongo.rb', line 399

def pluck(*fields)
  normalized_select = fields.inject({}) do |hash, f|
    hash[klass.database_field_name(f)] = 1
    hash
  end

  view.projection(normalized_select).map do |doc|
    if normalized_select.size == 1
      doc[normalized_select.keys.first]
    else
      normalized_select.keys.map { |n| doc[n] }
    end
  end
end