Method: Mongo::Collection#insert

Defined in:
lib/mongo/collection.rb

#insert(doc_or_docs, opts = {}) ⇒ ObjectId, ... Also known as: <<

Insert one or more documents into the collection.

Parameters:

  • doc_or_docs (Hash, Array)

    a document (as a hash) or array of documents to be inserted.

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

    a customizable set of options

Options Hash (opts):

  • :w, (Hash)

    :j, :wtimeout, :fsync Set the write concern for this operation. :w > 0 will run a getlasterror command on the database to report any assertion. :j will confirm a write has been committed to the journal, :wtimeout specifies how long to wait for write confirmation, :fsync will confirm that a write has been fsynced. Options provided here will override any write concern options set on this collection, its database object, or the current connection. See the options for DB#get_last_error.

  • :continue_on_error (Boolean) — default: +false+

    If true, then continue a bulk insert even if one of the documents inserted triggers a database assertion (as in a duplicate insert, for instance). If not acknowledging writes, the list of ids returned will include the object ids of all documents attempted on insert, even if some are rejected on error. When acknowledging writes, any error will raise an OperationFailure exception. MongoDB v2.0+.

  • :collect_on_error (Boolean) — default: +false+

    if true, then collects invalid documents as an array. Note that this option changes the result format.

Returns:

  • (ObjectId, Array)

    The _id of the inserted document or a list of _ids of all inserted documents.

  • ([ObjectId, Array], [Hash, Array])

    1st, the _id of the inserted document or a list of _ids of all inserted documents. 2nd, a list of invalid documents. Return this result format only when :collect_on_error is true.

Raises:



377
378
379
380
381
382
383
# File 'lib/mongo/collection.rb', line 377

def insert(doc_or_docs, opts={})
  doc_or_docs = [doc_or_docs] unless doc_or_docs.is_a?(Array)
  doc_or_docs.collect! { |doc| @pk_factory.create_pk(doc) }
  write_concern = get_write_concern(opts, self)
  result = insert_documents(doc_or_docs, @name, true, write_concern, opts)
  result.size > 1 ? result : result.first
end