Class: Mongo::DB

Inherits:
Object show all
Defined in:
lib/mongo/db.rb

Overview

A MongoDB database.

Constant Summary

SYSTEM_NAMESPACE_COLLECTION =
"system.namespaces"
SYSTEM_INDEX_COLLECTION =
"system.indexes"
SYSTEM_PROFILE_COLLECTION =
"system.profile"
SYSTEM_USER_COLLECTION =
"system.users"
SYSTEM_JS_COLLECTION =
"system.js"
SYSTEM_COMMAND_COLLECTION =
"$cmd"
@@current_request_id =

Counter for generating unique request ids.

0

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (DB) initialize(name, connection, opts = {})

Instances of DB are normally obtained by calling Mongo#db.

Parameters:

  • name (String)

    the database name.

  • connection (Mongo::Connection)

    a connection object pointing to MongoDB. Note that databases are usually instantiated via the Connection class. See the examples below.

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

    a customizable set of options

Options Hash (opts):

  • :strict (Boolean) — default: False

    If true, collections must exist to be accessed and must not exist to be created. See DB#collection and DB#create_collection.

  • :pk (Object, #create_pk(doc)) — default: Mongo::ObjectId

    A primary key factory object, which should take a hash and return a hash which merges the original hash with any primary key fields the factory wishes to inject. (NOTE: if the object already has a primary key, the factory should not inject a new key).

  • :safe (Boolean, Hash) — default: false

    Set the default safe-mode options propagated to Collection objects instantiated off of this DB. If no value is provided, the default value set on this instance's Connection object will be used. This default can be overridden upon instantiation of any collection by explicity setting a :safe value on initialization

  • :cache_time (Integer) — default: 300

    Set the time that all ensure_index calls should cache the command.



79
80
81
82
83
84
85
86
# File 'lib/mongo/db.rb', line 79

def initialize(name, connection, opts={})
  @name       = Mongo::Support.validate_db_name(name)
  @connection = connection
  @strict     = opts[:strict]
  @pk_factory = opts[:pk]
  @safe       = opts.fetch(:safe, @connection.safe)
  @cache_time = opts[:cache_time] || 300 #5 minutes.
end

Instance Attribute Details

- (Object) cache_time

The length of time that Collection.ensure_index should cache index calls



55
56
57
# File 'lib/mongo/db.rb', line 55

def cache_time
  @cache_time
end

- (Object) connection (readonly)

The Mongo::Connection instance connecting to the MongoDB server.



52
53
54
# File 'lib/mongo/db.rb', line 52

def connection
  @connection
end

- (Object) name (readonly)

The name of the database and the local safe option.



49
50
51
# File 'lib/mongo/db.rb', line 49

def name
  @name
end

- (Object) safe (readonly)

The name of the database and the local safe option.



49
50
51
# File 'lib/mongo/db.rb', line 49

def safe
  @safe
end

- (Object) strict=(value) (writeonly)

Strict mode enforces collection existence checks. When true, asking for a collection that does not exist, or trying to create a collection that already exists, raises an error.

Strict mode is disabled by default, but enabled (true) at any time.



43
44
45
# File 'lib/mongo/db.rb', line 43

def strict=(value)
  @strict = value
end

Instance Method Details

- (String) add_stored_function(function_name, code)

Adds a stored Javascript function to the database which can executed server-side in map_reduce, db.eval and $where clauses.

Parameters:

Returns:

  • (String)

    the function name saved to the database



141
142
143
144
145
146
147
148
# File 'lib/mongo/db.rb', line 141

def add_stored_function(function_name, code)
  self[SYSTEM_JS_COLLECTION].save(
    {
      "_id" => function_name, 
      :value => BSON::Code.new(code)
    }
  )
end

- (Hash) add_user(username, password)

Adds a user to this database for use with authentication. If the user already exists in the system, the password will be updated.

Parameters:

Returns:

  • (Hash)

    an object representing the user.



171
172
173
174
175
176
177
# File 'lib/mongo/db.rb', line 171

def add_user(username, password)
  users = self[SYSTEM_USER_COLLECTION]
  user  = users.find_one({:user => username}) || {:user => username}
  user['pwd'] = Mongo::Support.hash_password(username, password)
  users.save(user)
  return user
end

- (Boolean) authenticate(username, password, save_auth = true)

Authenticate with the given username and password. Note that mongod must be started with the --auth option for authentication to be enabled.

Parameters:

  • username (String)
  • password (String)
  • save_auth (Boolean) (defaults to: true)

    Save this authentication to the connection object using Connection#add_auth. This will ensure that the authentication will be applied on database reconnect. Note that this value must be true when using connection pooling.

Returns:

  • (Boolean)

Raises:



103
104
105
106
107
108
109
110
111
112
# File 'lib/mongo/db.rb', line 103

def authenticate(username, password, save_auth=true)
  if @connection.pool_size > 1
    if !save_auth
      raise MongoArgumentError, "If using connection pooling, :save_auth must be set to true."
    end
    @connection.authenticate_pools
  end

  issue_authentication(username, password, save_auth)
end

- (Mongo::Collection) collection(name, opts = {}) Also known as: []

Get a collection by name.

Parameters:

  • name (String)

    the collection name.

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

    any valid options that can be passed to Collection#new.

Returns:

Raises:

  • (MongoDBError)

    if collection does not already exist and we're in strict mode.



295
296
297
298
299
300
301
302
303
304
# File 'lib/mongo/db.rb', line 295

def collection(name, opts={})
  if strict? && !collection_names.include?(name)
    raise Mongo::MongoDBError, "Collection #{name} doesn't exist. Currently in strict mode."
  else
    opts = opts.dup
    opts[:safe] = opts.fetch(:safe, @safe)
    opts.merge!(:pk => @pk_factory) unless opts[:pk]
    Collection.new(name, self, opts)
  end
end

- (Array) collection_names

Get an array of collection names in this database.

Returns:

  • (Array)


221
222
223
224
225
# File 'lib/mongo/db.rb', line 221

def collection_names
  names = collections_info.collect { |doc| doc['name'] || '' }
  names = names.delete_if {|name| name.index(@name).nil? || name.index('$')}
  names.map {|name| name.sub(@name + '.', '')}
end

- (Array<Mongo::Collection>) collections

Get an array of Collection instances, one for each collection in this database.

Returns:



230
231
232
233
234
# File 'lib/mongo/db.rb', line 230

def collections
  collection_names.map do |name|
    Collection.new(name, self)
  end
end

- (Mongo::Cursor) collections_info(coll_name = nil)

Get info on system namespaces (collections). This method returns a cursor which can be iterated over. For each collection, a hash will be yielded containing a 'name' string and, optionally, an 'options' hash.

Parameters:

  • coll_name (String) (defaults to: nil)

    return info for the specifed collection only.

Returns:



243
244
245
246
247
# File 'lib/mongo/db.rb', line 243

def collections_info(coll_name=nil)
  selector = {}
  selector[:name] = full_collection_name(coll_name) if coll_name
  Cursor.new(Collection.new(SYSTEM_NAMESPACE_COLLECTION, self), :selector => selector)
end

- (Hash) command(selector, opts = {})

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:



484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
# File 'lib/mongo/db.rb', line 484

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

- (Mongo::Collection) create_collection(name, opts = {})

Create a collection.

new collection. If strict is true, will raise an error if collection name already exists.

Parameters:

  • name (String)

    the name of the new collection.

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

    a customizable set of options

Options Hash (opts):

  • :capped (Boolean) — default: False

    created a capped collection.

  • :size (Integer) — default: Nil

    If capped is true, specifies the maximum number of bytes for the capped collection. If false, specifies the number of bytes allocated for the initial extent of the collection.

  • :max (Integer) — default: Nil

    If capped is true, indicates the maximum number of records in a capped collection.

Returns:

Raises:

  • (MongoDBError)

    raised under two conditions: either we're in strict mode and the collection already exists or collection creation fails on the server.



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/mongo/db.rb', line 269

def create_collection(name, opts={})
  # Does the collection already exist?
  if collection_names.include?(name)
    if strict?
      raise MongoDBError, "Collection #{name} already exists. Currently in strict mode."
    else
      return Collection.new(name, self, opts)
    end
  end

  # Create a new collection.
  oh = BSON::OrderedHash.new
  oh[:create] = name
  doc = command(oh.merge(opts || {}))
  return Collection.new(name, self, :pk => @pk_factory) if ok?(doc)
  raise MongoDBError, "Error creating collection: #{doc.inspect}"
end

- (Hash) dereference(dbref)

Dereference a DBRef, returning the document it points to.

Parameters:

  • dbref (Mongo::DBRef)

Returns:

  • (Hash)

    the document indicated by the db reference.

See Also:



376
377
378
# File 'lib/mongo/db.rb', line 376

def dereference(dbref)
  collection(dbref.namespace).find_one("_id" => dbref.object_id)
end

- (Boolean) drop_collection(name)

Drop a collection by name.

Parameters:

Returns:

  • (Boolean)

    true on success or false if the collection name doesn't exist.



312
313
314
315
316
# File 'lib/mongo/db.rb', line 312

def drop_collection(name)
  return true unless collection_names.include?(name)

  ok?(command(:drop => name))
end

- (True) drop_index(collection_name, index_name)

Drop an index from a given collection. Normally called from Collection#drop_index or Collection#drop_indexes.

Parameters:

Returns:

  • (True)

    returns true on success.

Raises:

  • MongoDBError if there's an error renaming the collection.



424
425
426
427
428
429
430
# File 'lib/mongo/db.rb', line 424

def drop_index(collection_name, index_name)
  oh = BSON::OrderedHash.new
  oh[:deleteIndexes] = collection_name
  oh[:index] = index_name.to_s
  doc = command(oh, :check_response => false)
  ok?(doc) || raise(MongoDBError, "Error with drop_index command: #{doc.inspect}")
end

- (Boolean) error?

Return true if an error was caused by the most recently executed database operation.

Returns:

  • (Boolean)


340
341
342
# File 'lib/mongo/db.rb', line 340

def error?
  get_last_error['err'] != nil
end

- (String) eval(code, *args)

Evaluate a JavaScript expression in MongoDB.

Parameters:

  • code (String, Code)

    a JavaScript expression to evaluate server-side.

  • args (Integer, Hash)

    any additional argument to be passed to the code expression when it's run on the server.

Returns:

  • (String)

    the return value of the function.



387
388
389
390
391
392
393
394
395
396
397
# File 'lib/mongo/db.rb', line 387

def eval(code, *args)
  if not code.is_a? BSON::Code
    code = BSON::Code.new(code)
  end

  oh = BSON::OrderedHash.new
  oh[:$eval] = code
  oh[:args]  = args
  doc = command(oh)
  doc['retval']
end

- (String) full_collection_name(collection_name)

A shortcut returning db plus dot plus collection name.

Parameters:

Returns:



513
514
515
# File 'lib/mongo/db.rb', line 513

def full_collection_name(collection_name)
  "#{@name}.#{collection_name}"
end

- (Hash) get_last_error(opts = {})

Run the getlasterror command with the specified replication options.

Parameters:

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

    a customizable set of options

Options Hash (opts):

  • :fsync (Boolean) — default: false
  • :w (Integer) — default: nil
  • :wtimeout (Integer) — default: nil

Returns:

  • (Hash)

    the entire response to getlasterror.

Raises:



327
328
329
330
331
332
333
334
# File 'lib/mongo/db.rb', line 327

def get_last_error(opts={})
  cmd = BSON::OrderedHash.new
  cmd[:getlasterror] = 1
  cmd.merge!(opts)
  doc = command(cmd, :check_response => false)
  raise MongoDBError, "error retrieving last error: #{doc.inspect}" unless ok?(doc)
  doc
end

- (Hash) index_information(collection_name)

Get information on the indexes for the given collection. Normally called by Collection#index_information.

Parameters:

Returns:

  • (Hash)

    keys are index names and the values are lists of [key, direction] pairs defining the index.



439
440
441
442
443
444
445
446
# File 'lib/mongo/db.rb', line 439

def index_information(collection_name)
  sel  = {:ns => full_collection_name(collection_name)}
  info = {}
  Cursor.new(Collection.new(SYSTEM_INDEX_COLLECTION, self), :selector => sel).each do |index|
    info[index['name']] = index
  end
  info
end

- (Object) issue_authentication(username, password, save_auth = true, opts = {})

Raises:



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/mongo/db.rb', line 114

def issue_authentication(username, password, save_auth=true, opts={})
  doc = command({:getnonce => 1}, :check_response => false, :socket => opts[:socket])
  raise MongoDBError, "Error retrieving nonce: #{doc}" unless ok?(doc)
  nonce = doc['nonce']

  auth = BSON::OrderedHash.new
  auth['authenticate'] = 1
  auth['user'] = username
  auth['nonce'] = nonce
  auth['key'] = Mongo::Support.auth_key(username, password, nonce)
  if ok?(self.command(auth, :check_response => false, :socket => opts[:socket]))
    if save_auth
      @connection.add_auth(@name, username, password)
    end
    true
  else
    raise(Mongo::AuthenticationError, "Failed to authenticate user '#{username}' on db '#{self.name}'")
  end
end

- (Object) issue_logout(opts = {})



208
209
210
211
212
213
214
215
216
# File 'lib/mongo/db.rb', line 208

def issue_logout(opts={})
  doc = command({:logout => 1}, :socket => opts[:socket])
  if ok?(doc)
    @connection.remove_auth(@name)
    true
  else
    raise MongoDBError, "error logging out: #{doc.inspect}"
  end
end

- (Boolean) logout(opts = {})

Deauthorizes use for this database for this connection. Also removes any saved authentication in the connection class associated with this database.

Returns:

  • (Boolean)

Raises:



200
201
202
203
204
205
206
# File 'lib/mongo/db.rb', line 200

def logout(opts={})
  if @connection.pool_size > 1
    @connection.logout_pools(@name)
  end

  issue_logout(opts)
end

- (Boolean) ok?(doc)

Return true if the supplied doc contains an 'ok' field with the value 1.

Parameters:

Returns:

  • (Boolean)


460
461
462
# File 'lib/mongo/db.rb', line 460

def ok?(doc)
  Mongo::Support.ok?(doc)
end

- (Object, Nil) pk_factory

The primary key factory object (or nil).

Returns:



520
521
522
# File 'lib/mongo/db.rb', line 520

def pk_factory
  @pk_factory
end

- (Object) pk_factory=(pk_factory)

Specify a primary key factory if not already set.

Raises:



527
528
529
530
531
532
533
# File 'lib/mongo/db.rb', line 527

def pk_factory=(pk_factory)
  if @pk_factory
    raise MongoArgumentError, "Cannot change primary key factory once it's been set"
  end

  @pk_factory = pk_factory
end

- (String, Nil) previous_error

Get the most recent error to have occured on this database.

This command only returns errors that have occured since the last call to DB#reset_error_history - returns nil if there is no such error.

Returns:

  • (String, Nil)

    the text of the error or nil if no error has occurred.



350
351
352
353
354
355
356
357
# File 'lib/mongo/db.rb', line 350

def previous_error
  error = command(:getpreverror => 1)
  if error["err"]
    error
  else
    nil
  end
end

- (Array) profiling_info

Get the current profiling information.

Returns:

  • (Array)

    a list of documents containing profiling information.



581
582
583
# File 'lib/mongo/db.rb', line 581

def profiling_info
  Cursor.new(Collection.new(SYSTEM_PROFILE_COLLECTION, self), :selector => {}).to_a
end

- (Symbol) profiling_level

Return the current database profiling level. If profiling is enabled, you can get the results using DB#profiling_info.

Returns:

  • (Symbol)

    :off, :slow_only, or :all



541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
# File 'lib/mongo/db.rb', line 541

def profiling_level
  oh = BSON::OrderedHash.new
  oh[:profile] = -1
  doc = command(oh, :check_response => false)
  raise "Error with profile command: #{doc.inspect}" unless ok?(doc) && doc['was'].kind_of?(Numeric)
  case doc['was'].to_i
  when 0
    :off
  when 1
    :slow_only
  when 2
    :all
  else
    raise "Error: illegal profiling level value #{doc['was']}"
  end
end

- (Object) profiling_level=(level)

Set this database's profiling level. If profiling is enabled, you can get the results using DB#profiling_info.

Parameters:

  • level (Symbol)

    acceptable options are :off, :slow_only, or :all.



562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# File 'lib/mongo/db.rb', line 562

def profiling_level=(level)
  oh = BSON::OrderedHash.new
  oh[:profile] = case level
                 when :off
                   0
                 when :slow_only
                   1
                 when :all
                   2
                 else
                   raise "Error: illegal profiling level value #{level}"
                 end
  doc = command(oh, :check_response => false)
  ok?(doc) || raise(MongoDBError, "Error with profile command: #{doc.inspect}")
end

- (Boolean) remove_stored_function(function_name)

Removes stored Javascript function from the database. Returns false if the function does not exist

Parameters:

Returns:

  • (Boolean)


156
157
158
159
160
161
162
# File 'lib/mongo/db.rb', line 156

def remove_stored_function(function_name)
  if self[SYSTEM_JS_COLLECTION].find_one({"_id" => function_name})
    self[SYSTEM_JS_COLLECTION].remove({"_id" => function_name}, :safe => true)
  else
    return false
  end
end

- (Boolean) remove_user(username)

Remove the given user from this database. Returns false if the user doesn't exist in the system.

Parameters:

Returns:

  • (Boolean)


185
186
187
188
189
190
191
# File 'lib/mongo/db.rb', line 185

def remove_user(username)
  if self[SYSTEM_USER_COLLECTION].find_one({:user => username})
    self[SYSTEM_USER_COLLECTION].remove({:user => username}, :safe => true)
  else
    return false
  end
end

- (True) rename_collection(from, to)

Rename a collection.

Parameters:

  • from (String)

    original collection name.

  • to (String)

    new collection name.

Returns:

  • (True)

    returns true on success.

Raises:

  • MongoDBError if there's an error renaming the collection.



407
408
409
410
411
412
413
# File 'lib/mongo/db.rb', line 407

def rename_collection(from, to)
  oh = BSON::OrderedHash.new
  oh[:renameCollection] = "#{@name}.#{from}"
  oh[:to] = "#{@name}.#{to}"
  doc = DB.new('admin', @connection).command(oh, :check_response => false)
  ok?(doc) || raise(MongoDBError, "Error renaming collection: #{doc.inspect}")
end

- (Hash) reset_error_history

Reset the error history of this database

Calls to DB#previous_error will only return errors that have occurred since the most recent call to this method.

Returns:



365
366
367
# File 'lib/mongo/db.rb', line 365

def reset_error_history
  command(:reseterror => 1)
end

- (Hash) stats

Return stats on this database. Uses MongoDB's dbstats command.

Returns:



451
452
453
# File 'lib/mongo/db.rb', line 451

def stats
  self.command({:dbstats => 1})
end

- (Boolean) strict?

Returns the value of the strict flag.

Returns:

  • (Boolean)


46
# File 'lib/mongo/db.rb', line 46

def strict?; @strict; end

- (Hash) validate_collection(name)

Validate a named collection.

Parameters:

  • name (String)

    the collection name.

Returns:

  • (Hash)

    validation information.

Raises:

  • (MongoDBError)

    if the command fails or there's a problem with the validation data, or if the collection is invalid.



593
594
595
596
597
598
599
600
# File 'lib/mongo/db.rb', line 593

def validate_collection(name)
  doc = command({:validate => name}, :check_response => false)
  raise MongoDBError, "Error with validate command: #{doc.inspect}" unless ok?(doc)
  result = doc['result']
  raise MongoDBError, "Error with validation data: #{doc.inspect}" unless result.kind_of?(String)
  raise MongoDBError, "Error: invalid collection #{name}: #{doc.inspect}" if result =~ /\b(exception|corrupt)\b/i
  doc
end