module Mongoid::Relations::Embedded::Batchable

Contains behaviour for executing operations in batch on embedded documents.

Public Instance Methods

batch_clear(docs) click to toggle source

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

@example Clear all docs.

batchable.batch_clear(docs)

@param [ Array<Document> ] docs The docs to clear.

@return [ Array ] The empty array.

@since 3.0.0

# 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(
      positionally(selector, "$unset" => { path => true })
    )
    post_process_batch_remove(docs, :delete)
  end
  _unscoped.clear
end
batch_insert(docs) click to toggle source

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.

@example Execute the batch push.

batchable.batch_insert([ doc_one, doc_two ])

@param [ Array<Document> ] docs The docs to add.

@return [ Array<Hash> ] The inserts.

@since 3.0.0

# File lib/mongoid/relations/embedded/batchable.rb, line 22
def batch_insert(docs)
  execute_batch_insert(docs, "$pushAll")
end
batch_remove(docs, method = :delete) click to toggle source

Batch remove the provided documents as a $pullAll.

@example Batch remove the documents.

batchable.batch_remove([ doc_one, doc_two ])

@param [ Array<Document> ] docs The docs to remove. @param [ Symbol ] method Delete or destroy.

@since 3.0.0

# File lib/mongoid/relations/embedded/batchable.rb, line 56
def batch_remove(docs, method = :delete)
  removals = pre_process_batch_remove(docs, method)
  if !docs.empty?
    collection.find(selector).update(
      positionally(selector, "$pullAll" => { path => removals })
    )
    post_process_batch_remove(docs, method)
  end
  reindex
end
batch_replace(docs) click to toggle source

Batch replace the provided documents as a $set.

@example Batch replace the documents.

batchable.batch_replace([ doc_one, doc_two ])

@param [ Array<Document> ] docs The docs to replace with.

@return [ Array<Hash> ] The inserts.

@since 3.0.0

# File lib/mongoid/relations/embedded/batchable.rb, line 77
def batch_replace(docs)
  if docs.blank?
    if _assigning? && !empty?
      base.add_atomic_unset(first)
    end
    batch_remove(target.dup)
  else
    base.delayed_atomic_sets.clear unless _assigning?
    docs = normalize_docs(docs).compact
    target.clear and _unscoped.clear
    inserts = execute_batch_insert(docs, "$set")
    add_atomic_sets(inserts)
  end
end