Method: Mongoid::Persistable::Pushable#push

Defined in:
lib/mongoid/persistable/pushable.rb

#push(pushes) ⇒ Document

Push a single value or multiple values onto arrays.

Examples:

Push a single value onto arrays.

document.push(names: "James", aliases: "007")

Push multiple values onto arrays.

document.push(names: [ "James", "Bond" ])

Parameters:

  • pushes (Hash)

    The $push operations.

Returns:



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/mongoid/persistable/pushable.rb', line 51

def push(pushes)
  prepare_atomic_operation do |ops|
    process_atomic_operations(pushes) do |field, value|
      existing = send(field) || begin
        attributes[field] ||= []
        attributes[field]
      end
      values = [ value ].flatten(1)
      values.each{ |val| existing.push(val) }
      ops[atomic_attribute_name(field)] = { "$each" => values }
    end
    { "$push" => ops }
  end
end