Class: Mongo::DB

Inherits:
Object show all
Includes:
WriteConcern
Defined in:
lib/mongo/db.rb,
lib/mongo/legacy.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'
MAX_TIME_MS_CODE =
50
PROFILE_LEVEL =
{
  :off       => 0,
  :slow_only => 1,
  :all       => 2
}
@@current_request_id =

Counter for generating unique request ids.

0

Constants included from WriteConcern

WriteConcern::DEFAULT_WRITE_CONCERN, WriteConcern::VALID_KEYS

Instance Attribute Summary (collapse)

Attributes included from WriteConcern

#legacy_write_concern

Instance Method Summary (collapse)

Methods included from WriteConcern

#get_write_concern, gle?, #write_concern_from_legacy

Constructor Details

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

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

performed during a number of relevant operations. See DB#collection, DB#create_collection and DB#drop_collection.

Parameters:

  • name (String)

    the database name.

  • client (Mongo::MongoClient)

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

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

    a customizable set of options

Options Hash (opts):

  • :strict (Boolean) — default: False
    DEPRECATED

    If true, collections existence checks are

  • :pk (Object, #create_pk(doc)) — default: BSON::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).

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

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

  • :wtimeout (Integer) — default: nil

    Set replica set acknowledgement timeout.

  • :j (Boolean) — default: false

    If true, block until write operations have been committed to the journal. Cannot be used in combination with 'fsync'. Prior to MongoDB 2.6 this option was ignored if the server was running without journaling. Starting with MongoDB 2.6, write operations will fail with an exception if this option is used when the server is running without journaling.

  • :fsync (Boolean) — default: false

    If true, and the server is running without journaling, blocks until the server has synced all data files to disk. If the server is running with journaling, this acts the same as the 'j' option, blocking until write operations have been committed to the journal. Cannot be used in combination with 'j'.

    Notes on write concern:

    These write concern options are propagated to Collection objects instantiated off of this DB. If no
    options are provided, the default write concern set on this instance's MongoClient object will be used. This
    default can be overridden upon instantiation of any collection by explicitly setting write concern options
    on initialization or at the time of an operation.
  • :cache_time (Integer) — default: 300

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



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/mongo/db.rb', line 110

def initialize(name, client, opts={})
  # A database name of '$external' is permitted for some auth types
  Support.validate_db_name(name) unless name == '$external'

  @name       = name
  @client     = client
  @strict     = opts[:strict]
  @pk_factory = opts[:pk]

  @write_concern = get_write_concern(opts, client)

  @read = opts[:read] || @client.read
  ReadPreference::validate(@read)

  @tag_sets = opts.fetch(:tag_sets, @client.tag_sets)
  @acceptable_latency = opts.fetch(:acceptable_latency,
                                   @client.acceptable_latency)

  @cache_time = opts[:cache_time] || 300 #5 minutes.
end

Instance Attribute Details

- (Object) acceptable_latency

Read Preference



73
74
75
# File 'lib/mongo/db.rb', line 73

def acceptable_latency
  @acceptable_latency
end

- (Object) cache_time

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



70
71
72
# File 'lib/mongo/db.rb', line 70

def cache_time
  @cache_time
end

- (Object) client (readonly) Also known as: connection

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



64
65
66
# File 'lib/mongo/db.rb', line 64

def client
  @client
end

- (Object) name (readonly)

The name of the database and the local write concern options.



61
62
63
# File 'lib/mongo/db.rb', line 61

def name
  @name
end

- (Object) read

Read Preference



73
74
75
# File 'lib/mongo/db.rb', line 73

def read
  @read
end

- (Object) tag_sets

Read Preference



73
74
75
# File 'lib/mongo/db.rb', line 73

def tag_sets
  @tag_sets
end

- (Object) write_concern (readonly)

The name of the database and the local write concern options.



61
62
63
# File 'lib/mongo/db.rb', line 61

def write_concern
  @write_concern
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



180
181
182
183
184
185
186
187
# File 'lib/mongo/db.rb', line 180

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 = nil, read_only = false, opts = {})

Note:

The use of the opts argument to provide or update additional fields on the user document requires MongoDB >= 2.4.0

Adds a user to this database for use with authentication. If the user already exists in the system, the password and any additional fields provided in opts will be updated.

Parameters:

Returns:

  • (Hash)

    an object representing the user.



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/mongo/db.rb', line 219

def add_user(username, password=nil, read_only=false, opts={})
   = command(:usersInfo => username)
  if .key?('users') && !['users'].empty?
    create_or_update_user(:updateUser, username, password, read_only, opts)
  else
    create_or_update_user(:createUser, username, password, read_only, opts)
  end
    # MongoDB >= 2.5.3 requires the use of commands to manage users.
    # "Command not found" error didn't return an error code (59) before
    # MongoDB 2.4.7 so we assume that a nil error code means the usersInfo
    # command doesn't exist and we should fall back to the legacy add user code.
rescue OperationFailure => ex
  if Mongo::ErrorCode::COMMAND_NOT_FOUND_CODES.include?(ex.error_code)
    legacy_add_user(username, password, read_only, opts)
  elsif ex.error_code == Mongo::ErrorCode::UNAUTHORIZED
    # In MongoDB > 2.7 the localhost exception was narrowed, and the usersInfo
    # command is no longer allowed.  In this case, add the first user.
    create_or_update_user(:createUser, username, password, read_only, opts)
  else
    raise ex
  end
end

- (Boolean) authenticate(username, password = nil, save_auth = nil, source = nil, mechanism = nil, extra = nil)

Note:

The ability to disable the save_auth option has been deprecated. With save_auth=false specified, driver authentication behavior during failovers and reconnections becomes unreliable. This option still exists for API compatibility, but it no longer has any effect if disabled and now always uses the default behavior (safe_auth=true).

Authenticate with the given username and password.

Parameters:

  • username (String)

    The username.

  • password (String) (defaults to: nil)

    The user's password. This is not required for some authentication mechanisms.

  • save_auth (Boolean) (defaults to: nil)

    Save this authentication to the client object using MongoClient#add_auth. This will ensure that the authentication will be applied to all sockets and upon database reconnect.

  • source (String) (defaults to: nil)

    Database with user credentials. This should be used to authenticate against a database when the credentials exist elsewhere.

  • mechanism (String) (defaults to: nil)

    The authentication mechanism to be used.

  • extra (Hash) (defaults to: nil)

    A optional hash of extra options to be stored with the credential set.

Returns:

  • (Boolean)

    The result of the authentication operation.

Raises:



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

def authenticate(username, password=nil, save_auth=nil, source=nil, mechanism=nil, extra=nil)
  warn "[DEPRECATED] Disabling the 'save_auth' option no longer has " +
       "any effect. Please see the API documentation for more details " +
       "on this change." unless save_auth.nil?
  @client.add_auth(self.name, username, password, source, mechanism, extra)
  true
end

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

Get a collection by name.

Parameters:

  • name (String, Symbol)

    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.



366
367
368
369
370
371
372
373
374
# File 'lib/mongo/db.rb', line 366

def collection(name, opts={})
  if strict? && !collection_names.include?(name.to_s)
    raise MongoDBError, "Collection '#{name}' doesn't exist. (strict=true)"
  else
    opts = opts.dup
    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)


261
262
263
264
265
266
267
268
269
270
# File 'lib/mongo/db.rb', line 261

def collection_names
  if @client.wire_version_feature?(Mongo::MongoClient::MONGODB_2_8)
    names = collections_info.collect { |doc| doc['name'] || '' }
    names.delete_if do |name|
      name.index('$')
    end
  else
    legacy_collection_names
  end
end

- (Array<Mongo::Collection>) collections

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

Returns:



275
276
277
278
279
# File 'lib/mongo/db.rb', line 275

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

- (Array) 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 specified collection only.

Returns:

  • (Array)

    List of collection info.



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/mongo/db.rb', line 288

def collections_info(coll_name=nil)
  if @client.wire_version_feature?(Mongo::MongoClient::MONGODB_2_8)
    cmd = BSON::OrderedHash[:listCollections, 1]
    cmd.merge!(:filter => { :name => coll_name }) if coll_name
    result = self.command(cmd, :cursor => {})
    if result.key?('cursor')
      cursor_info = result['cursor']
      pinned_pool = @client.pinned_pool
      pinned_pool = pinned_pool[:pool] if pinned_pool.respond_to?(:keys)

      seed = {
        :cursor_id => cursor_info['id'],
        :first_batch => cursor_info['firstBatch'],
        :pool => pinned_pool,
        :ns => cursor_info['ns']
      }

      Cursor.new(Collection.new('$cmd', self), seed).to_a
    else
      result['collections']
    end
  else
    legacy_collections_info(coll_name).to_a
  end
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 and above, OrderedHash isn't necessary because hashes are ordered by default.

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 command fails.

  • :socket (Socket)

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

  • :read (:primary, :secondary)

    Read preference for this command. See Collection#find for more details.

  • :comment (String) — default: nil

    a comment to include in profiling logs

  • :compile_regex (Boolean) — default: true

    whether BSON regex objects should be compiled into Ruby regexes. If false, a BSON::Regex object will be returned instead.

Returns:

Raises:



576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# File 'lib/mongo/db.rb', line 576

def command(selector, opts={})
  raise MongoArgumentError, "Command must be given a selector" unless selector.respond_to?(:keys) && !selector.empty?

  opts = opts.dup
  # deletes :check_response and returns the value, if nil defaults to the block result
  check_response = opts.delete(:check_response) { true }

  # build up the command hash
  command = opts.key?(:socket) ? { :socket => opts.delete(:socket) } : {}
  command.merge!(:comment => opts.delete(:comment)) if opts.key?(:comment)
  command.merge!(:compile_regex => opts.delete(:compile_regex)) if opts.key?(:compile_regex)
  command[:limit] = -1
  command[:read] = Mongo::ReadPreference::cmd_read_pref(opts.delete(:read), selector) if opts.key?(:read)

  if RUBY_VERSION < '1.9' && selector.class != BSON::OrderedHash
    if selector.keys.length > 1
      raise MongoArgumentError, "DB#command requires an OrderedHash when hash contains multiple keys"
    end
    if opts.keys.size > 0
      # extra opts will be merged into the selector, so make sure it's an OH in versions < 1.9
      selector = selector.dup
      selector = BSON::OrderedHash.new.merge!(selector)
    end
  end

  # arbitrary opts are merged into the selector
  command[:selector] = selector.merge!(opts)

  begin
    result = Cursor.new(system_command_collection, command).next_document
  rescue OperationFailure => ex
    if check_response
      raise ex.class.new("Database command '#{selector.keys.first}' failed: #{ex.message}", ex.error_code, ex.result)
    else
      result = ex.result
    end
  end

  raise OperationFailure,
    "Database command '#{selector.keys.first}' failed: returned null." unless result

  if check_response && (!ok?(result) || result['writeErrors'] || result['writeConcernError'])
    message = "Database command '#{selector.keys.first}' failed: ("
    message << result.map do |key, value|
      "#{key}: '#{value}'"
    end.join('; ')
    message << ').'
    code = result['code'] || result['assertionCode']
    if result['writeErrors']
      code = result['writeErrors'].first['code']
    end
    raise ExecutionTimeout.new(message, code, result) if code == MAX_TIME_MS_CODE
    raise OperationFailure.new(message, code, result)
  end

  result
end

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

Note:

Note that the options listed may be subset of those available. Please see the MongoDB documentation for a full list of supported options by server version.

Create a collection.

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

Parameters:

  • name (String, Symbol)

    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.



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/mongo/db.rb', line 339

def create_collection(name, opts={})
  name = name.to_s
  if strict? && collection_names.include?(name)
    raise MongoDBError, "Collection '#{name}' already exists. (strict=true)"
  end

  begin
    cmd = BSON::OrderedHash.new
    cmd[:create] = name
    doc = command(cmd.merge(opts || {}))
    return Collection.new(name, self, :pk => @pk_factory) if ok?(doc)
  rescue OperationFailure => e
    return Collection.new(name, self, :pk => @pk_factory) if e.message =~ /exists/
    raise e
  end
  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:



446
447
448
# File 'lib/mongo/db.rb', line 446

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.



382
383
384
385
386
387
388
389
# File 'lib/mongo/db.rb', line 382

def drop_collection(name)
  return false if strict? && !collection_names.include?(name.to_s)
  begin
    ok?(command(:drop => name))
  rescue OperationFailure
    false
  end
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 dropping the index.



495
496
497
498
499
500
501
# File 'lib/mongo/db.rb', line 495

def drop_index(collection_name, index_name)
  cmd = BSON::OrderedHash.new
  cmd[:deleteIndexes] = collection_name
  cmd[:index] = index_name.to_s
  doc = command(cmd, :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)


414
415
416
# File 'lib/mongo/db.rb', line 414

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.



457
458
459
460
461
462
463
464
465
466
467
468
# File 'lib/mongo/db.rb', line 457

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

  cmd = BSON::OrderedHash.new
  cmd[:$eval] = code
  cmd.merge!(args.pop) if args.last.respond_to?(:keys) && args.last.key?(:nolock)
  cmd[:args] = args
  doc = command(cmd)
  doc['retval']
end

- (String) full_collection_name(collection_name)

A shortcut returning db plus dot plus collection name.

Parameters:

Returns:



639
640
641
# File 'lib/mongo/db.rb', line 639

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
  • :j (Boolean) — default: false

Returns:

  • (Hash)

    the entire response to getlasterror.

Raises:



401
402
403
404
405
406
407
408
# File 'lib/mongo/db.rb', line 401

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, type] pairs defining the index.



510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
# File 'lib/mongo/db.rb', line 510

def index_information(collection_name)
  if @client.wire_version_feature?(Mongo::MongoClient::MONGODB_2_8)
    result = self.command({ :listIndexes => collection_name }, :cursor => {})
    if result.key?('cursor')
      cursor_info = result['cursor']
      pinned_pool = @client.pinned_pool
      pinned_pool = pinned_pool[:pool] if pinned_pool.respond_to?(:keys)

      seed = {
        :cursor_id => cursor_info['id'],
        :first_batch => cursor_info['firstBatch'],
        :pool => pinned_pool,
        :ns => cursor_info['ns']
      }

      indexes = Cursor.new(Collection.new('$cmd', self), seed).to_a
    else
      indexes = result['indexes']
    end
  else
    indexes = legacy_list_indexes(collection_name)
  end
  indexes.reduce({}) do |info, index|
    info.merge!(index['name'] => index)
  end
end

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

Deprecated.

Please use MongoClient#issue_authentication instead. Support will be removed after v2.0



124
125
126
127
128
129
130
131
132
# File 'lib/mongo/legacy.rb', line 124

def issue_authentication(username, password, save_auth=true, opts={})
  auth = Authentication.validate_credentials({
    :db_name  => self.name,
    :username => username,
    :password => password
  })
  opts[:save_auth] = save_auth
  @client.issue_authentication(auth, opts)
end

- (Object) issue_logout(opts = {})

Deprecated.

Please use MongoClient#issue_logout instead. Support will be removed after v2.0



136
137
138
# File 'lib/mongo/legacy.rb', line 136

def issue_logout(opts={})
  @client.issue_logout(self.name, opts)
end

- (Boolean) logout(opts = {})

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

Returns:

  • (Boolean)


168
169
170
171
# File 'lib/mongo/db.rb', line 168

def logout(opts={})
  @client.remove_auth(self.name)
  true
end

- (Boolean) ok?(doc)

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

Parameters:

Returns:

  • (Boolean)


549
550
551
# File 'lib/mongo/db.rb', line 549

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

- (Object, Nil) pk_factory

The primary key factory object (or nil).

Returns:



646
647
648
# File 'lib/mongo/db.rb', line 646

def pk_factory
  @pk_factory
end

- (Object) pk_factory=(pk_factory)

Specify a primary key factory if not already set.

Raises:



653
654
655
656
657
658
# File 'lib/mongo/db.rb', line 653

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

  @pk_factory = pk_factory
end

- (String, Nil) previous_error

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

This command only returns errors that have occurred 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.



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

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

- (Array) profiling_info

Get the current profiling information.

Returns:

  • (Array)

    a list of documents containing profiling information.



690
691
692
# File 'lib/mongo/db.rb', line 690

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



664
665
666
667
668
669
670
671
672
673
674
# File 'lib/mongo/db.rb', line 664

def profiling_level
  cmd = BSON::OrderedHash.new
  cmd[:profile] = -1
  doc = command(cmd, :check_response => false)

  raise "Error with profile command: #{doc.inspect}" unless ok?(doc)

  level_sym = PROFILE_LEVEL.invert[doc['was'].to_i]
  raise "Error: illegal profiling level value #{doc['was']}" unless level_sym
  level_sym
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.



680
681
682
683
684
685
# File 'lib/mongo/db.rb', line 680

def profiling_level=(level)
  cmd = BSON::OrderedHash.new
  cmd[:profile] = PROFILE_LEVEL[level]
  doc = command(cmd, :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)


195
196
197
198
# File 'lib/mongo/db.rb', line 195

def remove_stored_function(function_name)
  return false unless self[SYSTEM_JS_COLLECTION].find_one({"_id" => function_name})
  self[SYSTEM_JS_COLLECTION].remove({"_id" => function_name}, :w => 1)
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)


248
249
250
251
252
253
254
255
256
# File 'lib/mongo/db.rb', line 248

def remove_user(username)
  begin
    command(:dropUser => username)
  rescue OperationFailure => ex
    raise ex unless Mongo::ErrorCode::COMMAND_NOT_FOUND_CODES.include?(ex.error_code)
    response = self[SYSTEM_USER_COLLECTION].remove({:user => username}, :w => 1)
    response.key?('n') && response['n'] > 0 ? response : 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.



478
479
480
481
482
483
484
# File 'lib/mongo/db.rb', line 478

def rename_collection(from, to)
  cmd = BSON::OrderedHash.new
  cmd[:renameCollection] = "#{@name}.#{from}"
  cmd[:to] = "#{@name}.#{to}"
  doc = DB.new('admin', @client).command(cmd, :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:



435
436
437
# File 'lib/mongo/db.rb', line 435

def reset_error_history
  command(:reseterror => 1)
end

- (Hash) stats

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

Returns:



540
541
542
# File 'lib/mongo/db.rb', line 540

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

- (Object) strict=(value)

Deprecated.

Support for strict will be removed in version 2.0 of the driver.

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.



45
46
47
48
49
50
51
# File 'lib/mongo/db.rb', line 45

def strict=(value)
  unless ENV['TEST_MODE']
    warn "Support for strict mode has been deprecated and will be " +
         "removed in version 2.0 of the driver."
  end
  @strict = value
end

- (Boolean) strict?

Deprecated.

Support for strict will be removed in version 2.0 of the driver.

Returns the value of the strict flag.

Returns:

  • (Boolean)


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

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.



702
703
704
705
706
707
708
709
710
711
712
713
714
# File 'lib/mongo/db.rb', line 702

def validate_collection(name)
  cmd = BSON::OrderedHash.new
  cmd[:validate] = name
  cmd[:full] = true
  doc = command(cmd, :check_response => false)

  raise MongoDBError, "Error with validate command: #{doc.inspect}" unless ok?(doc)

  if (doc.has_key?('valid') && !doc['valid']) || (doc['result'] =~ /\b(exception|corrupt)\b/i)
    raise MongoDBError, "Error: invalid collection #{name}: #{doc.inspect}"
  end
  doc
end