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'- PROFILE_LEVEL =
{ :off => 0, :slow_only => 1, :all => 2 }
- @@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 ⇒ Object
Read Preference.
-
#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 = nil, read_only = false, opts = {}) ⇒ Hash
Adds a user to this database for use with authentication.
-
#authenticate(username, password = nil, save_auth = true, source = nil) ⇒ 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=(value) ⇒ Object
deprecated
Deprecated.
Support for strict will be removed in version 2.0 of the driver.
-
#strict? ⇒ Boolean
deprecated
Deprecated.
Support for strict will be removed in version 2.0 of the driver.
-
#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.
performed during a number of relevant operations. See DB#collection, DB#create_collection and DB#drop_collection.
104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
# File 'lib/mongo/db.rb', line 104 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) @read = opts[:read] || @connection.read Mongo::ReadPreference::validate(@read) @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
72 73 74 |
# File 'lib/mongo/db.rb', line 72 def acceptable_latency @acceptable_latency end |
#cache_time ⇒ Object
The length of time that Collection.ensure_index should cache index calls
69 70 71 |
# File 'lib/mongo/db.rb', line 69 def cache_time @cache_time end |
#connection ⇒ Object (readonly)
The Mongo::MongoClient instance connecting to the MongoDB server.
66 67 68 |
# File 'lib/mongo/db.rb', line 66 def connection @connection end |
#name ⇒ Object (readonly)
The name of the database and the local write concern options.
63 64 65 |
# File 'lib/mongo/db.rb', line 63 def name @name end |
#tag_sets ⇒ Object
Read Preference
72 73 74 |
# File 'lib/mongo/db.rb', line 72 def tag_sets @tag_sets end |
#write_concern ⇒ Object (readonly)
The name of the database and the local write concern options.
63 64 65 |
# File 'lib/mongo/db.rb', line 63 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.
187 188 189 190 191 192 193 194 |
# File 'lib/mongo/db.rb', line 187 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 = nil, read_only = false, opts = {}) ⇒ Hash
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.
226 227 228 229 230 231 232 233 234 235 236 237 238 239 |
# File 'lib/mongo/db.rb', line 226 def add_user(username, password=nil, read_only=false, opts={}) users = self[SYSTEM_USER_COLLECTION] user = users.find_one({:user => username}) || {:user => username} user['pwd'] = Mongo::Support.hash_password(username, password) if password user['readOnly'] = true if read_only user.merge!(opts) begin users.save(user) rescue OperationFailure => ex # adding first admin user fails GLE in MongoDB 2.2 raise ex unless ex. =~ /login/ end user end |
#authenticate(username, password = nil, save_auth = true, source = nil) ⇒ Boolean
save_auth must be true when using connection pooling or providing a source for credentials.
Authenticate with the given username and password. Note that mongod must be started with the –auth option for authentication to be enabled.
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 |
# File 'lib/mongo/db.rb', line 139 def authenticate(username, password=nil, save_auth=true, source=nil) if (@connection.pool_size > 1 || source) && !save_auth raise MongoArgumentError, "If using connection pooling or delegated auth, " + ":save_auth must be set to true." end begin socket = @connection.checkout_reader(:mode => :primary_preferred) issue_authentication(username, password, save_auth, :socket => socket, :source => source) ensure socket.checkin if socket end @connection.authenticate_pools true end |
#collection(name, opts = {}) ⇒ Mongo::Collection Also known as: []
Get a collection by name.
356 357 358 359 360 361 362 363 364 |
# File 'lib/mongo/db.rb', line 356 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 |
#collection_names ⇒ Array
Get an array of collection names in this database.
279 280 281 282 283 |
# File 'lib/mongo/db.rb', line 279 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.
288 289 290 291 292 |
# File 'lib/mongo/db.rb', line 288 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.
301 302 303 304 305 |
# File 'lib/mongo/db.rb', line 301 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.
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 |
# File 'lib/mongo/db.rb', line 547 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 if read_pref = opts[:read] Mongo::ReadPreference::validate(read_pref) unless read_pref == :primary || Mongo::Support::secondary_ok?(selector) raise MongoArgumentError, "Command is not supported on secondaries: #{selector.keys.first}" end end begin result = Cursor.new( system_command_collection, :limit => -1, :selector => selector, :socket => socket, :read => read_pref, :comment => opts[:comment]).next_document rescue OperationFailure => ex raise OperationFailure, "Database command '#{selector.keys.first}' failed: #{ex.}" end raise OperationFailure, "Database command '#{selector.keys.first}' failed: returned null." unless result if 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) end result 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.
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 |
# File 'lib/mongo/db.rb', line 329 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. =~ /exists/ raise e end raise MongoDBError, "Error creating collection: #{doc.inspect}" end |
#dereference(dbref) ⇒ Hash
Dereference a DBRef, returning the document it points to.
436 437 438 |
# File 'lib/mongo/db.rb', line 436 def dereference(dbref) collection(dbref.namespace).find_one("_id" => dbref.object_id) end |
#drop_collection(name) ⇒ Boolean
Drop a collection by name.
372 373 374 375 376 377 378 379 |
# File 'lib/mongo/db.rb', line 372 def drop_collection(name) return false if strict? && !collection_names.include?(name.to_s) begin ok?(command(:drop => name)) rescue OperationFailure false end 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.
484 485 486 487 488 489 490 |
# File 'lib/mongo/db.rb', line 484 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 |
#error? ⇒ Boolean
Return true if an error was caused by the most recently executed database operation.
404 405 406 |
# File 'lib/mongo/db.rb', line 404 def error? get_last_error['err'] != nil end |
#eval(code, *args) ⇒ String
Evaluate a JavaScript expression in MongoDB.
447 448 449 450 451 452 453 454 455 456 457 |
# File 'lib/mongo/db.rb', line 447 def eval(code, *args) unless code.is_a?(BSON::Code) code = BSON::Code.new(code) end cmd = BSON::OrderedHash.new cmd[:$eval] = code cmd[:args] = args doc = command(cmd) doc['retval'] end |
#full_collection_name(collection_name) ⇒ String
A shortcut returning db plus dot plus collection name.
596 597 598 |
# File 'lib/mongo/db.rb', line 596 def full_collection_name(collection_name) "#{@name}.#{collection_name}" end |
#get_last_error(opts = {}) ⇒ Hash
Run the getlasterror command with the specified replication options.
391 392 393 394 395 396 397 398 |
# File 'lib/mongo/db.rb', line 391 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.
499 500 501 502 503 504 505 506 |
# File 'lib/mongo/db.rb', line 499 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
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
# File 'lib/mongo/db.rb', line 157 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'] # issue authentication against this database if source option not provided source = opts[:source] db = source ? @connection[source] : self 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 = db.command(auth, :check_response => false, :socket => opts[:socket])) @connection.add_auth(name, username, password, source) if save_auth else = "Failed to authenticate user '#{username}' on db '#{db.name}'" raise Mongo::AuthenticationError.new(, doc['code'], doc) end true end |
#issue_logout(opts = {}) ⇒ Object
269 270 271 272 273 274 |
# File 'lib/mongo/db.rb', line 269 def issue_logout(opts={}) unless ok?(doc = command({:logout => 1}, :socket => opts[:socket])) raise MongoDBError, "Error logging out: #{doc.inspect}" end true 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.
262 263 264 265 266 267 |
# File 'lib/mongo/db.rb', line 262 def logout(opts={}) auth = @connection.auths.find { |a| a[:db_name] == name } db = auth && auth[:source] ? @connection[auth[:source]] : self auth ? @connection.logout_pools(db.name) : db.issue_logout(opts) @connection.remove_auth(db.name) end |
#ok?(doc) ⇒ Boolean
Return true if the supplied doc contains an ‘ok’ field with the value 1.
520 521 522 |
# File 'lib/mongo/db.rb', line 520 def ok?(doc) Mongo::Support.ok?(doc) end |
#pk_factory ⇒ Object, Nil
The primary key factory object (or nil).
603 604 605 |
# File 'lib/mongo/db.rb', line 603 def pk_factory @pk_factory end |
#pk_factory=(pk_factory) ⇒ Object
Specify a primary key factory if not already set.
610 611 612 613 614 615 |
# File 'lib/mongo/db.rb', line 610 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 |
#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.
414 415 416 417 |
# File 'lib/mongo/db.rb', line 414 def previous_error error = command(:getpreverror => 1) error["err"] ? error : nil end |
#profiling_info ⇒ Array
Get the current profiling information.
649 650 651 |
# File 'lib/mongo/db.rb', line 649 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.
623 624 625 626 627 628 629 630 631 632 633 |
# File 'lib/mongo/db.rb', line 623 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 |
#profiling_level=(level) ⇒ Object
Set this database’s profiling level. If profiling is enabled, you can get the results using DB#profiling_info.
639 640 641 642 643 644 |
# File 'lib/mongo/db.rb', line 639 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 |
#remove_stored_function(function_name) ⇒ Boolean
Removes stored Javascript function from the database. Returns false if the function does not exist
202 203 204 205 |
# File 'lib/mongo/db.rb', line 202 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 |
#remove_user(username) ⇒ Boolean
Remove the given user from this database. Returns false if the user doesn’t exist in the system.
247 248 249 250 251 252 253 |
# File 'lib/mongo/db.rb', line 247 def remove_user(username) if self[SYSTEM_USER_COLLECTION].find_one({:user => username}) self[SYSTEM_USER_COLLECTION].remove({:user => username}, :w => 1) else false end end |
#rename_collection(from, to) ⇒ True
Rename a collection.
467 468 469 470 471 472 473 |
# File 'lib/mongo/db.rb', line 467 def rename_collection(from, to) cmd = BSON::OrderedHash.new cmd[:renameCollection] = "#{@name}.#{from}" cmd[:to] = "#{@name}.#{to}" doc = DB.new('admin', @connection).command(cmd, :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.
425 426 427 |
# File 'lib/mongo/db.rb', line 425 def reset_error_history command(:reseterror => 1) end |
#stats ⇒ Hash
Return stats on this database. Uses MongoDB’s dbstats command.
511 512 513 |
# File 'lib/mongo/db.rb', line 511 def stats self.command({:dbstats => 1}) end |
#strict=(value) ⇒ Object
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.
47 48 49 50 51 52 53 |
# File 'lib/mongo/db.rb', line 47 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 |
#strict? ⇒ Boolean
Support for strict will be removed in version 2.0 of the driver.
Returns the value of the strict flag.
58 59 60 |
# File 'lib/mongo/db.rb', line 58 def strict? @strict end |
#validate_collection(name) ⇒ Hash
Validate a named collection.
661 662 663 664 665 666 667 668 669 670 671 672 673 |
# File 'lib/mongo/db.rb', line 661 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 |