Module: Mongoid::Persistable::Pushable

Extended by:
ActiveSupport::Concern
Included in:
Mongoid::Persistable
Defined in:
build/mongoid-7.0/lib/mongoid/persistable/pushable.rb

Overview

Defines behaviour for $push and $addToSet operations.

Since:

  • 4.0.0

Instance Method Summary collapse

Instance Method Details

#add_to_set(adds) ⇒ Document

Add the single values to the arrays only if the value does not already exist in the array.

Examples:

Add the values to the sets.

document.add_to_set(names: "James", aliases: "Bond")

Parameters:

  • adds (Hash)

    The field/value pairs to add.

Returns:

Since:

  • 4.0.0



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'build/mongoid-7.0/lib/mongoid/persistable/pushable.rb', line 22

def add_to_set(adds)
  prepare_atomic_operation do |ops|
    process_atomic_operations(adds) do |field, value|
      existing = send(field) || attributes[field]
      if existing.nil?
        attributes[field] = []
        # Read the value out of attributes:
        # https://jira.mongodb.org/browse/MONGOID-4874
        existing = attributes[field]
      end
      values = [ value ].flatten(1)
      values.each do |val|
        existing.push(val) unless existing.include?(val)
      end
      ops[atomic_attribute_name(field)] = { "$each" => values }
    end
    { "$addToSet" => ops }
  end
end

#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:

Since:

  • 4.0.0



55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'build/mongoid-7.0/lib/mongoid/persistable/pushable.rb', line 55

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