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:

  • The document to insert.

  • (defaults to: {})

    The insert options.

  • a customizable set of 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:

  • The database response wrapper.

Since:

  • 2.0.0



849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
# File 'lib/mongo/collection.rb', line 849

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

  client.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,
      operation_timeouts: operation_timeouts(opts)
      )
    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