123456789_123456789_123456789_123456789_123456789_

Module: Mongoid::Persistable::Upsertable

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Included In:
Defined in: lib/mongoid/persistable/upsertable.rb

Overview

Defines behavior for persistence operations that upsert documents.

Instance Method Summary

Instance Method Details

#prepare_upsert(options = {}) ⇒ true | false (private)

This method is for internal use only.

Prepare the upsert for execution.

Examples:

Prepare the upsert

document.prepare_upsert do
  collection.find(selector).update(as_document)
end

Parameters:

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

    The options hash.

Options Hash (options):

  • :validate (true | false)

    Whether or not to validate.

Returns:

  • (true | false)

    If the operation succeeded.

Raises:

[ GitHub ]

  
# File 'lib/mongoid/persistable/upsertable.rb', line 71

def prepare_upsert(options = {})
  raise Errors::ReadonlyDocument.new(self.class) if readonly? && !Mongoid.legacy_readonly
  return false if performing_validations?(options) && invalid?(:upsert)
  result = run_callbacks(:upsert) do
    yield(self)
    true
  end
  self.new_record = false
  post_process_persist(result, options) and result
end

#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 false in ::Mongoid 9.

Examples:

Upsert the document.

document.upsert

Upsert the document with replace.

document.upsert(replace: true)

Upsert with extra attributes to use when inserting.

document.upsert(set_on_insert: { created_at: DateTime.now })

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.

  • :set_on_insert (Hash)

    The attributes to include if the document does not already exist.

Returns:

  • (true)

    True.

[ GitHub ]

  
# File 'lib/mongoid/persistable/upsertable.rb', line 36

def upsert(options = {})
  prepare_upsert(options) do
    if options[:replace]
      if options[:set_on_insert]
        raise ArgumentError, "cannot specify :set_on_insert with `replace: true`"
      end

      collection.find(atomic_selector).replace_one(
        as_attributes, upsert: true, session: _session)
    else
      attrs = { "$set" => as_attributes }
      attrs["$setOnInsert"] = options[:set_on_insert] if options[:set_on_insert]

      collection.find(atomic_selector).update_one(
        attrs, upsert: true, session: _session)
    end
  end
end