Method: Mongo::DB#command

Defined in:
lib/mongo/db.rb

#command(selector, opts = {}) ⇒ Hash

Send a command to the database.

Note: DB commands must start with the “command” key. For this reason, any selector containing more than one key must be an OrderedHash.

Note also that a command in MongoDB is just a kind of query that occurs on the system command collection ($cmd). Examine this method’s implementation to see how it works.

key, specifying the command to be performed. In Ruby 1.9, OrderedHash isn’t necessary since hashes are ordered by default.

command fails.

Parameters:

  • selector (OrderedHash, Hash)

    an OrderedHash, or a standard Hash with just one

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

    a customizable set of options

Options Hash (opts):

  • :check_response (Boolean) — default: true

    If true, raises an exception if the

  • :socket (Socket)

    a socket to use for sending the command. This is mainly for internal use.

Returns:

Raises:



488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# File 'lib/mongo/db.rb', line 488

def command(selector, opts={})
  check_response = opts.fetch(:check_response, true)
  socket         = opts[:socket]
  raise MongoArgumentError, "command must be given a selector" unless selector.is_a?(Hash) && !selector.empty?
  if selector.keys.length > 1 && RUBY_VERSION < '1.9' && selector.class != BSON::OrderedHash
    raise MongoArgumentError, "DB#command requires an OrderedHash when hash contains multiple keys"
  end

  begin
    result = Cursor.new(system_command_collection,
      :limit => -1, :selector => selector, :socket => socket).next_document
  rescue OperationFailure => ex
    raise OperationFailure, "Database command '#{selector.keys.first}' failed: #{ex.message}"
  end

  if result.nil?
    raise OperationFailure, "Database command '#{selector.keys.first}' failed: returned null."
  elsif (check_response && !ok?(result))
    raise OperationFailure, "Database command '#{selector.keys.first}' failed: #{result.inspect}"
  else
    result
  end
end