Method: Mongo::Collection#insert_one

Defined in:
lib/mongo/collection.rb

#insert_one(document, opts = {}) ⇒ Result

Insert a single document into the collection.

Examples:

Insert a document into the collection.

collection.insert_one({ name: 'test' })

Parameters:

  • document (Hash)

    The document to insert.

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

    The insert options.

Options Hash (opts):

  • :session (Session)

    The session to use for the operation.

Returns:

  • (Result)

    The database response wrapper.

Since:

  • 2.0.0



586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
# File 'lib/mongo/collection.rb', line 586

def insert_one(document, opts = {})
  QueryCache.clear_namespace(namespace)

  client.send(:with_session, opts) do |session|
    write_concern = if opts[:write_concern]
      WriteConcern.get(opts[:write_concern])
    else
      write_concern_with_session(session)
    end

    if document.nil?
      raise ArgumentError, "Document to be inserted cannot be nil"
    end

    write_with_retry(session, write_concern) do |server, txn_num|
      Operation::Insert.new(
        :documents => [ document ],
        :db_name => database.name,
        :coll_name => name,
        :write_concern => write_concern,
        :bypass_document_validation => !!opts[:bypass_document_validation],
        :options => opts,
        :id_generator => client.options[:id_generator],
        :session => session,
        :txn_num => txn_num,
      ).execute(server, context: Operation::Context.new(client: client, session: session))
    end
  end
end