Module: Mongoid::Relations::Embedded::Batchable

Included in:
Many
Defined in:
lib/mongoid/relations/embedded/batchable.rb

Overview

Contains behaviour for executing operations in batch on embedded documents.

Instance Method Summary (collapse)

Instance Method Details

- (Array) batch_clear(docs)

Clear all of the docs out of the relation in a single swipe.

Examples:

Clear all docs.

batchable.batch_clear(docs)

Parameters:

  • docs (Array<Document>)

    The docs to clear.

Returns:

  • (Array)

    The empty array.

Since:

  • 3.0.0



36
37
38
39
40
41
42
43
# File 'lib/mongoid/relations/embedded/batchable.rb', line 36

def batch_clear(docs)
  pre_process_batch_remove(docs, :delete)
  unless docs.empty?
    collection.find(selector).update("$unset" => { path => true })
    post_process_batch_remove(docs, :delete)
  end
  _unscoped.clear
end

- (Array<Hash>) batch_insert(docs)

Insert new documents as a batch push ($pushAll). This ensures that all callbacks are run at the appropriate time and only 1 request is made to the database.

Examples:

Execute the batch push.

batchable.batch_insert([ doc_one, doc_two ])

Parameters:

  • docs (Array<Document>)

    The docs to add.

Returns:

  • (Array<Hash>)

    The inserts.

Since:

  • 3.0.0



22
23
24
# File 'lib/mongoid/relations/embedded/batchable.rb', line 22

def batch_insert(docs)
  execute_batch_insert(docs, "$pushAll")
end

- (Object) batch_remove(docs, method = :delete)

Batch remove the provided documents as a $pullAll.

Examples:

Batch remove the documents.

batchable.batch_remove([ doc_one, doc_two ])

Parameters:

  • docs (Array<Document>)

    The docs to remove.

  • method (Symbol) (defaults to: :delete)

    Delete or destroy.

Since:

  • 3.0.0



54
55
56
57
58
59
60
61
62
# File 'lib/mongoid/relations/embedded/batchable.rb', line 54

def batch_remove(docs, method = :delete)
  removals = pre_process_batch_remove(docs, method)
  if !docs.empty? && !_assigning?
    collection.find(selector).update("$pullAll" => { path => removals })
    post_process_batch_remove(docs, method)
  end
  Threaded.clear_options!
  reindex
end

- (Array<Hash>) batch_replace(docs)

Batch replace the provided documents as a $set.

Examples:

Batch replace the documents.

batchable.batch_replace([ doc_one, doc_two ])

Parameters:

  • docs (Array<Document>)

    The docs to replace with.

Returns:

  • (Array<Hash>)

    The inserts.

Since:

  • 3.0.0



74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/mongoid/relations/embedded/batchable.rb', line 74

def batch_replace(docs)
  if docs.blank?
    if _assigning? && !empty?
      base.atomic_unsets.push(first.atomic_path)
    end
    batch_remove(target.dup)
  else
    base.delayed_atomic_sets.clear
    docs = normalize_docs(docs).compact
    target.clear and _unscoped.clear
    inserts = execute_batch_insert(docs, "$set")
    add_atomic_sets(inserts)
  end
end