Method: Mongo::Collection#remove

Defined in:
lib/mongo/collection.rb

#remove(selector = {}, opts = {}) ⇒ Hash, true

Remove all documents from this collection.

Examples:

remove all documents from the ‘users’ collection:

users.remove
users.remove({})

remove only documents that have expired:

users.remove({:expire => {"$lte" => Time.now}})

Parameters:

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

    If specified, only matching documents will be removed.

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

    a customizable set of options

Options Hash (opts):

  • :w (String, Integer, Symbol) — default: 1

    Set default number of nodes to which a write should be acknowledged

  • :j (Boolean) — default: false

    Set journal acknowledgement

  • :wtimeout (Integer) — default: nil

    Set replica set acknowledgement timeout

  • :fsync (Boolean) — default: false

    Set fsync acknowledgement.

    Notes on write concern:

    Options provided here will override any write concern options set on this collection,
    its database object, or the current connection. See the options for +DB#get_last_error+.
    

Returns:

  • (Hash, true)

    Returns a Hash containing the last error object if acknowledging writes Otherwise, returns true.

Raises:



408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/mongo/collection.rb', line 408

def remove(selector={}, opts={})
  write_concern = get_write_concern(opts, self)
  message = BSON::ByteBuffer.new("\0\0\0\0", @connection.max_message_size)
  BSON::BSON_RUBY.serialize_cstr(message, "#{@db.name}.#{@name}")
  message.put_int(0)
  message.put_binary(BSON::BSON_CODER.serialize(selector, false, true, @connection.max_bson_size).to_s)

  instrument(:remove, :database => @db.name, :collection => @name, :selector => selector) do
    if Mongo::WriteConcern.gle?(write_concern)
      @connection.send_message_with_gle(Mongo::Constants::OP_DELETE, message, @db.name, nil, write_concern)
    else
      @connection.send_message(Mongo::Constants::OP_DELETE, message)
      true
    end
  end
end