Method: Mongo::Collection#insert

Defined in:
lib/mongo/collection.rb

#insert(doc_or_docs, opts = {}) ⇒ ObjectId, Array 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):

  • :safe (Boolean, Hash) — default: +false+

    run the operation in safe mode, which run a getlasterror command on the database to report any assertion. In addition, a hash can be provided to run an fsync and/or wait for replication of the insert (>= 1.5.1). Safe options provided here will override any safe options set on this collection, its database object, or the current connection. See the options on for DB#get_last_error.

Returns:

  • (ObjectId, Array)

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

See Also:

  • for options that can be passed to :safe.


279
280
281
282
283
284
285
# File 'lib/mongo/collection.rb', line 279

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) }
  safe = opts.fetch(:safe, @safe)
  result = insert_documents(doc_or_docs, @name, true, safe)
  result.size > 1 ? result : result.first
end