Method: Mongo::Collection::View::Writable#delete_one

Defined in:
lib/mongo/collection/view/writable.rb

#delete_one(opts = {}) ⇒ Result

Remove a document from the collection.

Examples:

Remove a single document from the collection.

collection_view.delete_one

Parameters:

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

    The options.

  • options (Hash)

    a customizable set of options

Options Hash (opts):

  • :collation (Hash)

    The collation to use.

  • :comment (Object)

    A user-provided comment to attach to this command.

  • :hint (Hash | String)

    The index to use for this operation. May be specified as a Hash (e.g. { _id: 1 }) or a String (e.g. “id”).

  • :let (Hash)

    Mapping of variables to use in the command. See the server documentation for details.

  • :session (Session)

    The session to use.

  • :write_concern (Hash)

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

Returns:

  • (Result)

    The response from the database.

Since:

  • 2.0.0



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/mongo/collection/view/writable.rb', line 323

def delete_one(opts = {})
  with_session(opts) do |session|
    write_concern = if opts[:write_concern]
      WriteConcern.get(opts[:write_concern])
    else
      write_concern_with_session(session)
    end

    QueryCache.clear_namespace(collection.namespace)

    delete_doc = {
      Operation::Q => filter,
      Operation::LIMIT => 1,
      hint: opts[:hint],
      collation: opts[:collation] || opts['collation'] || collation,
    }.compact

    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|
      gte_4_4 = connection.server.description.server_version_gte?('4.4')
      if !gte_4_4 && opts[:hint] && write_concern && !write_concern.acknowledged?
        raise Error::UnsupportedOption.hint_error(unacknowledged_write: true)
      end

      Operation::Delete.new(
        deletes: [ delete_doc ],
        db_name: collection.database.name,
        coll_name: collection.name,
        write_concern: write_concern,
        bypass_document_validation: !!opts[:bypass_document_validation],
        session: session,
        txn_num: txn_num,
        let: opts[:let],
        comment: opts[:comment],
      ).execute_with_connection(connection, context: context)
    end
  end
end