Class: Mongo::DB
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)
-
- (Object) cache_time
The length of time that Collection.ensure_index should cache index calls.
-
- (Object) connection
readonly
The Mongo::Connection instance connecting to the MongoDB server.
-
- (Object) name
readonly
The name of the database and the local safe option.
-
- (Object) safe
readonly
The name of the database and the local safe option.
-
- (Object) strict
writeonly
Strict mode enforces collection existence checks.
Instance Method Summary (collapse)
-
- (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.
-
- (Hash) add_user(username, password, read_only = false)
Adds a user to this database for use with authentication.
-
- (Boolean) authenticate(username, password, save_auth = true)
Authenticate with the given username and password.
-
- (Mongo::Collection) collection(name, opts = {})
(also: #[])
Get a collection by name.
-
- (Array) collection_names
Get an array of collection names in this database.
-
- (Array<Mongo::Collection>) collections
Get an array of Collection instances, one for each collection in this database.
-
- (Mongo::Cursor) collections_info(coll_name = nil)
Get info on system namespaces (collections).
-
- (Hash) command(selector, opts = {})
Send a command to the database.
-
- (Mongo::Collection) create_collection(name, opts = {})
Create a collection.
-
- (Hash) dereference(dbref)
Dereference a DBRef, returning the document it points to.
-
- (Boolean) drop_collection(name)
Drop a collection by name.
-
- (True) drop_index(collection_name, index_name)
Drop an index from a given collection.
-
- (Boolean) error?
Return true if an error was caused by the most recently executed database operation.
-
- (String) eval(code, *args)
Evaluate a JavaScript expression in MongoDB.
-
- (String) full_collection_name(collection_name)
A shortcut returning db plus dot plus collection name.
-
- (Hash) get_last_error(opts = {})
Run the getlasterror command with the specified replication options.
-
- (Hash) index_information(collection_name)
Get information on the indexes for the given collection.
-
- (DB) initialize(name, connection, opts = {})
constructor
Instances of DB are normally obtained by calling Mongo#db.
- - (Object) issue_authentication(username, password, save_auth = true, opts = {})
- - (Object) issue_logout(opts = {})
-
- (Boolean) logout(opts = {})
Deauthorizes use for this database for this connection.
-
- (Boolean) ok?(doc)
Return true if the supplied doc contains an 'ok' field with the value 1.
-
- (Object, Nil) pk_factory
The primary key factory object (or nil).
-
- (Object) pk_factory=(pk_factory)
Specify a primary key factory if not already set.
-
- (String, Nil) previous_error
Get the most recent error to have occured on this database.
-
- (Array) profiling_info
Get the current profiling information.
-
- (Symbol) profiling_level
Return the current database profiling level.
-
- (Object) profiling_level=(level)
Set this database's profiling level.
-
- (Object) read_preference
The value of the read preference.
-
- (Boolean) remove_stored_function(function_name)
Removes stored Javascript function from the database.
-
- (Boolean) remove_user(username)
Remove the given user from this database.
-
- (True) rename_collection(from, to)
Rename a collection.
-
- (Hash) reset_error_history
Reset the error history of this database.
-
- (Hash) stats
Return stats on this database.
-
- (Boolean) strict?
Returns the value of the strict flag.
-
- (Hash) validate_collection(name)
Validate a named collection.
Constructor Details
- (DB) initialize(name, connection, opts = {})
Instances of DB are normally obtained by calling Mongo#db.
Core docs:
78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
# File 'lib/mongo/db.rb', line 78 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) if value = opts[:read] Mongo::Support.validate_read_preference(value) else value = @connection.read_preference end @read_preference = value.is_a?(Hash) ? value.dup : value @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
54 55 56 |
# File 'lib/mongo/db.rb', line 54 def cache_time @cache_time end |
- (Object) connection (readonly)
The Mongo::Connection instance connecting to the MongoDB server.
51 52 53 |
# File 'lib/mongo/db.rb', line 51 def connection @connection end |
- (Object) name (readonly)
The name of the database and the local safe option.
48 49 50 |
# File 'lib/mongo/db.rb', line 48 def name @name end |
- (Object) safe (readonly)
The name of the database and the local safe option.
48 49 50 |
# File 'lib/mongo/db.rb', line 48 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.
42 43 44 |
# File 'lib/mongo/db.rb', line 42 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.
150 151 152 153 154 155 156 157 |
# File 'lib/mongo/db.rb', line 150 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, read_only = false)
Adds a user to this database for use with authentication. If the user already exists in the system, the password will be updated.
182 183 184 185 186 187 188 189 |
# File 'lib/mongo/db.rb', line 182 def add_user(username, password, read_only = false) users = self[SYSTEM_USER_COLLECTION] user = users.find_one({:user => username}) || {:user => username} user['pwd'] = Mongo::Support.hash_password(username, password) user['readOnly'] = true if read_only; 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.
Core docs:
108 109 110 111 112 113 114 115 116 117 118 119 120 |
# File 'lib/mongo/db.rb', line 108 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 end @connection.best_available_socket do |socket| issue_authentication(username, password, save_auth, :socket => socket) end @connection.authenticate_pools end |
- (Mongo::Collection) collection(name, opts = {}) Also known as: []
Get a collection by name.
311 312 313 314 315 316 317 318 319 320 321 |
# File 'lib/mongo/db.rb', line 311 def collection(name, opts={}) if strict? && !collection_names.include?(name.to_s) 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.
233 234 235 236 237 |
# File 'lib/mongo/db.rb', line 233 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.
242 243 244 245 246 |
# File 'lib/mongo/db.rb', line 242 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.
255 256 257 258 259 |
# File 'lib/mongo/db.rb', line 255 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.
Core docs:
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 |
# File 'lib/mongo/db.rb', line 502 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.}" end if result.nil? raise OperationFailure, "Database command '#{selector.keys.first}' failed: returned null." elsif (check_response && !ok?(result)) = "Database command '#{selector.keys.first}' failed: (" << result.map do |key, value| "#{key}: '#{value}'" end.join('; ') << ').' code = result['code'] || result['assertionCode'] raise OperationFailure.new(, code, result) 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.
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 |
# File 'lib/mongo/db.rb', line 283 def create_collection(name, opts={}) name = name.to_s 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.
394 395 396 |
# File 'lib/mongo/db.rb', line 394 def dereference(dbref) collection(dbref.namespace).find_one("_id" => dbref.object_id) end |
- (Boolean) drop_collection(name)
Drop a collection by name.
329 330 331 332 333 |
# File 'lib/mongo/db.rb', line 329 def drop_collection(name) return true unless collection_names.include?(name.to_s) 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.
442 443 444 445 446 447 448 |
# File 'lib/mongo/db.rb', line 442 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.
358 359 360 |
# File 'lib/mongo/db.rb', line 358 def error? get_last_error['err'] != nil end |
- (String) eval(code, *args)
Evaluate a JavaScript expression in MongoDB.
405 406 407 408 409 410 411 412 413 414 415 |
# File 'lib/mongo/db.rb', line 405 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.
537 538 539 |
# File 'lib/mongo/db.rb', line 537 def full_collection_name(collection_name) "#{@name}.#{collection_name}" end |
- (Hash) get_last_error(opts = {})
Run the getlasterror command with the specified replication options.
345 346 347 348 349 350 351 352 |
# File 'lib/mongo/db.rb', line 345 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.
457 458 459 460 461 462 463 464 |
# File 'lib/mongo/db.rb', line 457 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 = {})
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
# File 'lib/mongo/db.rb', line 122 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?(doc = self.command(auth, :check_response => false, :socket => opts[:socket])) if save_auth @connection.add_auth(@name, username, password) end true else = "Failed to authenticate user '#{username}' on db '#{self.name}'" raise Mongo::AuthenticationError.new(, doc['code'], doc) end end |
- (Object) issue_logout(opts = {})
220 221 222 223 224 225 226 227 228 |
# File 'lib/mongo/db.rb', line 220 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.
212 213 214 215 216 217 218 |
# File 'lib/mongo/db.rb', line 212 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.
478 479 480 |
# File 'lib/mongo/db.rb', line 478 def ok?(doc) Mongo::Support.ok?(doc) end |
- (Object, Nil) pk_factory
The primary key factory object (or nil).
544 545 546 |
# File 'lib/mongo/db.rb', line 544 def pk_factory @pk_factory end |
- (Object) pk_factory=(pk_factory)
Specify a primary key factory if not already set.
551 552 553 554 555 556 557 |
# File 'lib/mongo/db.rb', line 551 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.
368 369 370 371 372 373 374 375 |
# File 'lib/mongo/db.rb', line 368 def previous_error error = command(:getpreverror => 1) if error["err"] error else nil end end |
- (Array) profiling_info
Get the current profiling information.
605 606 607 |
# File 'lib/mongo/db.rb', line 605 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.
Core docs:
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 |
# File 'lib/mongo/db.rb', line 565 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.
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 |
# File 'lib/mongo/db.rb', line 586 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 |
- (Object) read_preference
The value of the read preference. This will be either :primary, :secondary, or an object representing the tags to be read from.
634 635 636 |
# File 'lib/mongo/db.rb', line 634 def read_preference @read_preference end |
- (Boolean) remove_stored_function(function_name)
Removes stored Javascript function from the database. Returns false if the function does not exist
165 166 167 168 169 170 171 |
# File 'lib/mongo/db.rb', line 165 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.
197 198 199 200 201 202 203 |
# File 'lib/mongo/db.rb', line 197 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.
425 426 427 428 429 430 431 |
# File 'lib/mongo/db.rb', line 425 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.
383 384 385 |
# File 'lib/mongo/db.rb', line 383 def reset_error_history command(:reseterror => 1) end |
- (Hash) stats
Return stats on this database. Uses MongoDB's dbstats command.
469 470 471 |
# File 'lib/mongo/db.rb', line 469 def stats self.command({:dbstats => 1}) end |
- (Boolean) strict?
Returns the value of the strict flag.
45 |
# File 'lib/mongo/db.rb', line 45 def strict?; @strict; end |
- (Hash) validate_collection(name)
Validate a named collection.
617 618 619 620 621 622 623 624 625 626 627 628 629 |
# File 'lib/mongo/db.rb', line 617 def validate_collection(name) cmd = BSON::OrderedHash.new cmd[:validate] = name cmd[:full] = true doc = command(cmd, :check_response => false) if !ok?(doc) raise MongoDBError, "Error with validate command: #{doc.inspect}" end 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 |