Module: Mongoid::Persistable::Upsertable

Included in:
Mongoid::Persistable
Defined in:
build/mongoid-8.1/lib/mongoid/persistable/upsertable.rb

Overview

Defines behavior for persistence operations that upsert documents.

Instance Method Summary collapse

Instance Method Details

#upsert(options = {}) ⇒ true

Perform an upsert of the document. If the document does not exist in the database, then Mongo will insert a new one, otherwise the fields will get overwritten with new values on the existing document.

If the replace option is true, unspecified attributes will be dropped, and if it is false, unspecified attributes will be maintained. The replace option defaults to true in Mongoid 8.1 and earlier. The default will be flipped to false in Mongoid 9.

Examples:

Upsert the document.

document.upsert

Upsert the document without replace.

document.upsert(replace: false)

Parameters:

  • options (Hash) (defaults to: {})

    The validation options.

Options Hash (options):

  • :validate (true | false)

    Whether or not to validate.

  • :replace (true | false)

    Whether or not to replace the document on upsert.

Returns:

  • (true)

    True.



30
31
32
33
34
35
36
37
38
39
40
# File 'build/mongoid-8.1/lib/mongoid/persistable/upsertable.rb', line 30

def upsert(options = {})
  prepare_upsert(options) do
    if options.fetch(:replace, true)
      collection.find(atomic_selector).replace_one(
        as_attributes, upsert: true, session: _session)
    else
      collection.find(atomic_selector).update_one(
        { "$set" => as_attributes }, upsert: true, session: _session)
    end
  end
end