Class: Mongo::DB
Overview
A MongoDB database.
Constant Summary collapse
- 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
-
#acceptable_latency ⇒ Object
Read Preference.
-
#cache_time ⇒ Object
The length of time that Collection.ensure_index should cache index calls.
-
#connection ⇒ Object
readonly
The Mongo::MongoClient instance connecting to the MongoDB server.
-
#name ⇒ Object
readonly
The name of the database and the local write concern options.
-
#read_preference ⇒ Object
Read Preference.
-
#strict ⇒ Object
writeonly
Strict mode enforces collection existence checks.
-
#tag_sets ⇒ Object
Read Preference.
-
#write_concern ⇒ Object
readonly
The name of the database and the local write concern options.
Attributes included from WriteConcern
Instance Method Summary collapse
-
#add_stored_function(function_name, code) ⇒ String
Adds a stored Javascript function to the database which can executed server-side in map_reduce, db.eval and $where clauses.
-
#add_user(username, password, read_only = false) ⇒ Hash
Adds a user to this database for use with authentication.
-
#authenticate(username, password, save_auth = true) ⇒ Boolean
Authenticate with the given username and password.
-
#collection(name, opts = {}) ⇒ Mongo::Collection
(also: #[])
Get a collection by name.
-
#collection_names ⇒ Array
Get an array of collection names in this database.
-
#collections ⇒ Array<Mongo::Collection>
Get an array of Collection instances, one for each collection in this database.
-
#collections_info(coll_name = nil) ⇒ Mongo::Cursor
Get info on system namespaces (collections).
-
#command(selector, opts = {}) ⇒ Hash
Send a command to the database.
-
#create_collection(name, opts = {}) ⇒ Mongo::Collection
Create a collection.
-
#dereference(dbref) ⇒ Hash
Dereference a DBRef, returning the document it points to.
-
#drop_collection(name) ⇒ Boolean
Drop a collection by
name. -
#drop_index(collection_name, index_name) ⇒ True
Drop an index from a given collection.
-
#error? ⇒ Boolean
Return
trueif an error was caused by the most recently executed database operation. -
#eval(code, *args) ⇒ String
Evaluate a JavaScript expression in MongoDB.
-
#full_collection_name(collection_name) ⇒ String
A shortcut returning db plus dot plus collection name.
-
#get_last_error(opts = {}) ⇒ Hash
Run the getlasterror command with the specified replication options.
-
#index_information(collection_name) ⇒ Hash
Get information on the indexes for the given collection.
-
#initialize(name, client, opts = {}) ⇒ DB
constructor
Instances of DB are normally obtained by calling Mongo#db.
- #issue_authentication(username, password, save_auth = true, opts = {}) ⇒ Object
- #issue_logout(opts = {}) ⇒ Object
-
#logout(opts = {}) ⇒ Boolean
Deauthorizes use for this database for this client connection.
-
#ok?(doc) ⇒ Boolean
Return
trueif the supplieddoccontains an ‘ok’ field with the value 1. -
#pk_factory ⇒ Object, Nil
The primary key factory object (or
nil). -
#pk_factory=(pk_factory) ⇒ Object
Specify a primary key factory if not already set.
-
#previous_error ⇒ String, Nil
Get the most recent error to have occurred on this database.
-
#profiling_info ⇒ Array
Get the current profiling information.
-
#profiling_level ⇒ Symbol
Return the current database profiling level.
-
#profiling_level=(level) ⇒ Object
Set this database’s profiling level.
-
#remove_stored_function(function_name) ⇒ Boolean
Removes stored Javascript function from the database.
-
#remove_user(username) ⇒ Boolean
Remove the given user from this database.
-
#rename_collection(from, to) ⇒ True
Rename a collection.
-
#reset_error_history ⇒ Hash
Reset the error history of this database.
-
#stats ⇒ Hash
Return stats on this database.
-
#strict? ⇒ Boolean
Returns the value of the
strictflag. -
#validate_collection(name) ⇒ Hash
Validate a named collection.
Methods included from WriteConcern
#get_write_concern, gle?, #write_concern_from_legacy
Constructor Details
#initialize(name, client, opts = {}) ⇒ DB
Instances of DB are normally obtained by calling Mongo#db.
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/mongo/db.rb', line 83 def initialize(name, client, opts={}) @name = Mongo::Support.validate_db_name(name) @connection = client @strict = opts[:strict] @pk_factory = opts[:pk] @write_concern = get_write_concern(opts, client) 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 @tag_sets = opts.fetch(:tag_sets, @connection.tag_sets) @acceptable_latency = opts.fetch(:acceptable_latency, @connection.acceptable_latency) @cache_time = opts[:cache_time] || 300 #5 minutes. end |
Instance Attribute Details
#acceptable_latency ⇒ Object
Read Preference
58 59 60 |
# File 'lib/mongo/db.rb', line 58 def acceptable_latency @acceptable_latency end |
#cache_time ⇒ Object
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 |
#connection ⇒ Object (readonly)
The Mongo::MongoClient instance connecting to the MongoDB server.
52 53 54 |
# File 'lib/mongo/db.rb', line 52 def connection @connection end |
#name ⇒ Object (readonly)
The name of the database and the local write concern options.
49 50 51 |
# File 'lib/mongo/db.rb', line 49 def name @name end |
#read_preference ⇒ Object
Read Preference
58 59 60 |
# File 'lib/mongo/db.rb', line 58 def read_preference @read_preference end |
#strict=(value) ⇒ Object (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 |
#tag_sets ⇒ Object
Read Preference
58 59 60 |
# File 'lib/mongo/db.rb', line 58 def tag_sets @tag_sets end |
#write_concern ⇒ Object (readonly)
The name of the database and the local write concern options.
49 50 51 |
# File 'lib/mongo/db.rb', line 49 def write_concern @write_concern end |
Instance Method Details
#add_stored_function(function_name, code) ⇒ String
Adds a stored Javascript function to the database which can executed
server-side in map_reduce, db.eval and $where clauses.
162 163 164 165 166 167 168 169 |
# File 'lib/mongo/db.rb', line 162 def add_stored_function(function_name, code) self[SYSTEM_JS_COLLECTION].save( { "_id" => function_name, :value => BSON::Code.new(code) } ) end |
#add_user(username, password, read_only = false) ⇒ Hash
Adds a user to this database for use with authentication. If the user already exists in the system, the password will be updated.
194 195 196 197 198 199 200 201 |
# File 'lib/mongo/db.rb', line 194 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 |
#authenticate(username, password, save_auth = true) ⇒ Boolean
Authenticate with the given username and password. Note that mongod must be started with the –auth option for authentication to be enabled.
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
# File 'lib/mongo/db.rb', line 117 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 begin socket = @connection.checkout_reader(:primary_preferred) issue_authentication(username, password, save_auth, :socket => socket) ensure socket.pool.checkin(socket) if socket end @connection.authenticate_pools end |
#collection(name, opts = {}) ⇒ Mongo::Collection Also known as: []
Get a collection by name.
323 324 325 326 327 328 329 330 331 332 |
# File 'lib/mongo/db.rb', line 323 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.merge!(:pk => @pk_factory) unless opts[:pk] Collection.new(name, self, opts) end end |
#collection_names ⇒ Array
Get an array of collection names in this database.
245 246 247 248 249 |
# File 'lib/mongo/db.rb', line 245 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 |
#collections ⇒ Array<Mongo::Collection>
Get an array of Collection instances, one for each collection in this database.
254 255 256 257 258 |
# File 'lib/mongo/db.rb', line 254 def collections collection_names.map do |name| Collection.new(name, self) end end |
#collections_info(coll_name = nil) ⇒ Mongo::Cursor
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.
267 268 269 270 271 |
# File 'lib/mongo/db.rb', line 267 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 |
#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.
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 |
# File 'lib/mongo/db.rb', line 513 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)) = "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 |
#create_collection(name, opts = {}) ⇒ Mongo::Collection
Create a collection.
new collection. If strict is true, will raise an error if collection name already exists.
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 |
# File 'lib/mongo/db.rb', line 295 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 |
#dereference(dbref) ⇒ Hash
Dereference a DBRef, returning the document it points to.
405 406 407 |
# File 'lib/mongo/db.rb', line 405 def dereference(dbref) collection(dbref.namespace).find_one("_id" => dbref.object_id) end |
#drop_collection(name) ⇒ Boolean
Drop a collection by name.
340 341 342 343 344 |
# File 'lib/mongo/db.rb', line 340 def drop_collection(name) return true unless collection_names.include?(name.to_s) ok?(command(:drop => name)) end |
#drop_index(collection_name, index_name) ⇒ True
Drop an index from a given collection. Normally called from Collection#drop_index or Collection#drop_indexes.
453 454 455 456 457 458 459 |
# File 'lib/mongo/db.rb', line 453 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 |
#error? ⇒ Boolean
Return true if an error was caused by the most recently executed database operation.
369 370 371 |
# File 'lib/mongo/db.rb', line 369 def error? get_last_error['err'] != nil end |
#eval(code, *args) ⇒ String
Evaluate a JavaScript expression in MongoDB.
416 417 418 419 420 421 422 423 424 425 426 |
# File 'lib/mongo/db.rb', line 416 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 |
#full_collection_name(collection_name) ⇒ String
A shortcut returning db plus dot plus collection name.
548 549 550 |
# File 'lib/mongo/db.rb', line 548 def full_collection_name(collection_name) "#{@name}.#{collection_name}" end |
#get_last_error(opts = {}) ⇒ Hash
Run the getlasterror command with the specified replication options.
356 357 358 359 360 361 362 363 |
# File 'lib/mongo/db.rb', line 356 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 |
#index_information(collection_name) ⇒ Hash
Get information on the indexes for the given collection. Normally called by Collection#index_information.
468 469 470 471 472 473 474 475 |
# File 'lib/mongo/db.rb', line 468 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 |
#issue_authentication(username, password, save_auth = true, opts = {}) ⇒ Object
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 |
# File 'lib/mongo/db.rb', line 134 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 |
#issue_logout(opts = {}) ⇒ Object
232 233 234 235 236 237 238 239 240 |
# File 'lib/mongo/db.rb', line 232 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 |
#logout(opts = {}) ⇒ Boolean
Deauthorizes use for this database for this client connection. Also removes any saved authentication in the MongoClient class associated with this database.
224 225 226 227 228 229 230 |
# File 'lib/mongo/db.rb', line 224 def logout(opts={}) if @connection.pool_size > 1 @connection.logout_pools(@name) end issue_logout(opts) end |
#ok?(doc) ⇒ Boolean
Return true if the supplied doc contains an ‘ok’ field with the value 1.
489 490 491 |
# File 'lib/mongo/db.rb', line 489 def ok?(doc) Mongo::Support.ok?(doc) end |
#pk_factory ⇒ Object, Nil
The primary key factory object (or nil).
555 556 557 |
# File 'lib/mongo/db.rb', line 555 def pk_factory @pk_factory end |
#pk_factory=(pk_factory) ⇒ Object
Specify a primary key factory if not already set.
562 563 564 565 566 567 568 |
# File 'lib/mongo/db.rb', line 562 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 |
#previous_error ⇒ String, Nil
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.
379 380 381 382 383 384 385 386 |
# File 'lib/mongo/db.rb', line 379 def previous_error error = command(:getpreverror => 1) if error["err"] error else nil end end |
#profiling_info ⇒ Array
Get the current profiling information.
616 617 618 |
# File 'lib/mongo/db.rb', line 616 def profiling_info Cursor.new(Collection.new(SYSTEM_PROFILE_COLLECTION, self), :selector => {}).to_a end |
#profiling_level ⇒ Symbol
Return the current database profiling level. If profiling is enabled, you can get the results using DB#profiling_info.
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 |
# File 'lib/mongo/db.rb', line 576 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 |
#profiling_level=(level) ⇒ Object
Set this database’s profiling level. If profiling is enabled, you can get the results using DB#profiling_info.
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 |
# File 'lib/mongo/db.rb', line 597 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 |
#remove_stored_function(function_name) ⇒ Boolean
Removes stored Javascript function from the database. Returns false if the function does not exist
177 178 179 180 181 182 183 |
# File 'lib/mongo/db.rb', line 177 def remove_stored_function(function_name) if self[SYSTEM_JS_COLLECTION].find_one({"_id" => function_name}) self[SYSTEM_JS_COLLECTION].remove({"_id" => function_name}, :w => 1) else return false end end |
#remove_user(username) ⇒ Boolean
Remove the given user from this database. Returns false if the user doesn’t exist in the system.
209 210 211 212 213 214 215 |
# File 'lib/mongo/db.rb', line 209 def remove_user(username) if self[SYSTEM_USER_COLLECTION].find_one({:user => username}) self[SYSTEM_USER_COLLECTION].remove({:user => username}, :w => 1) else return false end end |
#rename_collection(from, to) ⇒ True
Rename a collection.
436 437 438 439 440 441 442 |
# File 'lib/mongo/db.rb', line 436 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 |
#reset_error_history ⇒ Hash
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.
394 395 396 |
# File 'lib/mongo/db.rb', line 394 def reset_error_history command(:reseterror => 1) end |
#stats ⇒ Hash
Return stats on this database. Uses MongoDB’s dbstats command.
480 481 482 |
# File 'lib/mongo/db.rb', line 480 def stats self.command({:dbstats => 1}) end |
#strict? ⇒ Boolean
Returns the value of the strict flag.
46 |
# File 'lib/mongo/db.rb', line 46 def strict?; @strict; end |
#validate_collection(name) ⇒ Hash
Validate a named collection.
628 629 630 631 632 633 634 635 636 637 638 639 640 |
# File 'lib/mongo/db.rb', line 628 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 |