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):

  • :bypass_document_validation (true | false)

    Whether or not to skip document level validation.

  • :comment (Object)

    A user-provided comment to attach to this command.

  • :session (Session)

    The session to use for the operation.

  • :write_concern (Hash)

    The write concern options. Can be :w => Integer, :fsync => Boolean, :j => Boolean.

Returns:

  • (Result)

    The database response wrapper.

Since:

  • 2.0.0



790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
# File 'lib/mongo/collection.rb', line 790

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

    context = Operation::Context.new(client: client, session: session)
    write_with_retry(write_concern, context: context) do |connection, txn_num, context|
      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,
        :comment => opts[:comment]
      ).execute_with_connection(connection, context: context)
    end
  end
end