Class: Mongo::Database
| Relationships & Source Files | |
| Namespace Children | |
|
Classes:
| |
| Super Chains via Extension / Inclusion / Inheritance | |
|
Class Chain:
self,
Forwardable
|
|
|
Instance Chain:
self,
Retryable
|
|
| Inherits: | Object |
| Defined in: | lib/mongo/database.rb, lib/mongo/database/cursor_command_view.rb, lib/mongo/database/view.rb |
Overview
Represents a database on the db server and operations that can execute on it at this level.
Constant Summary
-
ADMIN =
# File 'lib/mongo/database.rb', line 32
The admin database name.
'admin' -
COMMAND =
# File 'lib/mongo/database.rb', line 37
The "collection" that database commands operate against.
'$cmd' -
DATABASES =
# File 'lib/mongo/database.rb', line 53
Databases constant.
'databases' -
DEFAULT_OPTIONS =
# File 'lib/mongo/database.rb', line 42
The default database options.
Options::Redacted.new(database: ADMIN).freeze
-
NAME =
# File 'lib/mongo/database.rb', line 48Deprecated.
Databasename field constant.'name' -
NAMESPACES =
# File 'lib/mongo/database.rb', line 58
The name of the collection that holds all the collection names.
'system.namespaces'
Class Method Summary
-
.create(client) ⇒ Database
Internal use only
Create a database for the provided client, for use when we don't want the client's original database instance to be the same.
-
.new(client, name, options = {}) ⇒ Database
constructor
Instantiate a new database object.
Instance Attribute Summary
- #client ⇒ Client readonly
- #name ⇒ String readonly
- #options ⇒ Hash readonly
Instance Method Summary
-
#==(other) ⇒ true, false
Check equality of the database object against another.
-
#[](collection_name, options = {}) ⇒ Mongo::Collection
(also: #collection)
Get a collection in this database by the provided name.
-
#aggregate(pipeline, options = {}) ⇒ Collection::View::Aggregation
Perform an aggregation on the database.
- #cluster ⇒ Mongo::Server
-
#collection(collection_name, options = {})
Alias for #[].
-
#collection_names(options = {}) ⇒ Array<String>
Get all the names of the non-system collections in the database.
-
#collections(options = {}) ⇒ Array<Mongo::Collection>
Get all the non-system collections that belong to this database.
-
#command(operation, opts = {}) ⇒ Mongo::Operation::Result
Execute a command on the database.
-
#cursor_command(command, options = {}) ⇒ Mongo::Cursor
Run a command that returns a cursor and parse the response as a cursor.
-
#drop(options = {}) ⇒ Result
Drop the database and all its associated information.
-
#fs(options = {}) ⇒ Grid::FSBucket
Get the
Grid"filesystem" for this database. -
#inspect ⇒ String
Get a pretty printed string inspection for the database.
-
#list_collections(options = {}) ⇒ Array<Hash>
Get info on all the non-system collections in the database.
- #operation_timeouts(opts) ⇒ Hash Internal use only
-
#read_command(operation, opts = {}) ⇒ Hash
Internal use only
Execute a read command on the database, retrying the read if necessary.
- #timeout_ms ⇒ Integer | nil Internal use only
-
#users ⇒ View::User
Get the user view for this database.
-
#watch(pipeline = [], options = {}) ⇒ ChangeStream
Allows users to request that notifications are sent for all changes that occur in the client's database.
-
#check_out_cursor_command_connection(server, context) ⇒ Server::Connection
private
Checks out a load balanced connection for a cursor command.
-
#extract_cursor_command_view_options(options) ⇒ Hash
private
Removes the getMore and cursor options from the options hash and returns them as a separate hash for the
CursorCommandView.
Retryable - Included
| #read_worker | Returns the read worker for handling retryable reads. |
| #select_server | This is a separate method to make it possible for the test suite to assert that server selection is performed during retry attempts. |
| #with_overload_retry | Wraps an operation with overload retry logic. |
| #write_worker | Returns the write worker for handling retryable writes. |
| #deprioritize_server? | Whether the failed server should be deprioritized during server selection for a retry attempt. |
Constructor Details
.new(client, name, options = {}) ⇒ Database
Instantiate a new database object.
# File 'lib/mongo/database.rb', line 479
def initialize(client, name, = {}) raise Error::InvalidDatabaseName.new unless name if Lint.enabled? && !(name.is_a?(String) || name.is_a?(Symbol)) raise "Database name must be a string or a symbol: #{name}" end @client = client @name = name.to_s.freeze @options = .freeze end
Class Method Details
.create(client) ⇒ Database
Create a database for the provided client, for use when we don't want the client's original database instance to be the same.
Instance Attribute Details
#client ⇒ Client (readonly)
# File 'lib/mongo/database.rb', line 61
attr_reader :client
#name ⇒ String (readonly)
# File 'lib/mongo/database.rb', line 64
attr_reader :name
#options ⇒ Hash (readonly)
# File 'lib/mongo/database.rb', line 67
attr_reader :
Instance Method Details
#==(other) ⇒ true, false
Check equality of the database object against another. Will simply check if the names are the same.
#[](collection_name, options = {}) ⇒ Mongo::Collection Also known as: #collection
Get a collection in this database by the provided name.
# File 'lib/mongo/database.rb', line 111
def [](collection_name, = {}) if [:server_api] raise ArgumentError, 'The :server_api option cannot be specified for collection objects. It can only be specified on Client level' end Collection.new(self, collection_name, ) end
#aggregate(pipeline, options = {}) ⇒ Collection::View::Aggregation
Perform an aggregation on the database.
#check_out_cursor_command_connection(server, context) ⇒ Server::Connection (private)
Checks out a load balanced connection for a cursor command. If the session is pinned to a connection (e.g. in a transaction), that connection is reused.
# File 'lib/mongo/database.rb', line 711
def check_out_cursor_command_connection(server, context) connection = if context.connection_global_id server.pool.check_out_pinned_connection(context.connection_global_id) end connection || server.pool.check_out(context: context) end
#cluster ⇒ Mongo::Server
# File 'lib/mongo/database.rb', line 80
def_delegators :cluster, :next_primary
#collection(collection_name, options = {})
Alias for #[].
# File 'lib/mongo/database.rb', line 119
alias collection []
#collection_names(options = {}) ⇒ Array<String>
The set of returned collection names depends on the version of MongoDB server that fulfills the request.
Get all the names of the non-system collections in the database.
See https://mongodb.com/docs/manual/reference/command/listCollections/
for more information and usage.
# File 'lib/mongo/database.rb', line 145
def collection_names( = {}) View.new(self, ).collection_names() end
#collections(options = {}) ⇒ Array<Mongo::Collection>
The set of returned collections depends on the version of MongoDB server that fulfills the request.
Get all the non-system collections that belong to this database.
See https://mongodb.com/docs/manual/reference/command/listCollections/
for more information and usage.
# File 'lib/mongo/database.rb', line 206
def collections( = {}) collection_names().map { |name| collection(name) } end
#command(operation, opts = {}) ⇒ Mongo::Operation::Result
Execute a command on the database.
# File 'lib/mongo/database.rb', line 232
def command(operation, opts = {}) opts = opts.dup execution_opts = opts.delete(:) || {} txn_read_pref = (opts[:session].txn_read_preference if opts[:session] && opts[:session].in_transaction?) txn_read_pref ||= opts[:read] || ServerSelector::PRIMARY Lint.validate_underscore_read_preference(txn_read_pref) selector = ServerSelector.get(txn_read_pref) client.with_session(opts) do |session| context = Operation::Context.new( client: client, session: session, operation_timeouts: operation_timeouts(opts) ) op = Operation::Command.new( selector: operation, db_name: name, read: selector, session: session ) retry_enabled = client.[:retry_reads] != false && client.[:retry_writes] != false with_overload_retry(context: context, retry_enabled: retry_enabled) do server = selector.select_server(cluster, nil, session) op.execute(server, context: context, options: execution_opts) end end end
#cursor_command(command, options = {}) ⇒ Mongo::Cursor
Run a command that returns a cursor and parse the response as a cursor.
The command is sent to the server unmodified; the driver MUST NOT inspect or alter it. If the response does not contain a cursor field an error is raised. The command is never retried.
Note: if a maxTimeMS field is already set on the command document it is
left as-is. The max_time_ms option below applies only to getMore
commands. Setting both #timeout_ms and max_time_ms is not supported
and has undefined behavior.
# File 'lib/mongo/database.rb', line 301
def cursor_command(command, = {}) = .dup execution_opts = .delete(:) || {} = () txn_read_pref = ([:session].txn_read_preference if [:session] && [:session].in_transaction?) txn_read_pref ||= [:read] || ServerSelector::PRIMARY Lint.validate_underscore_read_preference(txn_read_pref) selector = ServerSelector.get(txn_read_pref) # The session is intentionally not wrapped in #with_session: an implicit # session must outlive this method and is ended by the cursor when it is # exhausted or closed. Until the cursor takes ownership, the session and # any load-balanced connection are cleaned up here on every exit path. session = client.get_session() context = Operation::Context.new( client: client, session: session, operation_timeouts: operation_timeouts() ) op = Operation::CursorCommand.new( selector: command, db_name: name, read: selector, session: session ) # Per the client-backpressure spec, retrying a generic command on # overload errors requires both retryable reads and writes to be # enabled, same as Database#command. retry_enabled = client.[:retry_reads] != false && client.[:retry_writes] != false server = nil connection = nil cursor = nil begin result = with_overload_retry(context: context, retry_enabled: retry_enabled) do server = selector.select_server(cluster, nil, session) if server.load_balancer? # The connection is checked in by the cursor when it is drained. connection = check_out_cursor_command_connection(server, context) begin op.execute_with_connection(connection, context: context, options: execution_opts) rescue StandardError # Release the connection before the error propagates so that # a retried attempt checks out a fresh one. connection.connection_pool.check_in(connection) unless connection.pinned? connection = nil raise end else op.execute(server, context: context, options: execution_opts) end end unless result.cursor? raise Error::InvalidCursorOperation, 'The command response did not include a cursor. ' \ 'Use Database#command for commands that do not return a cursor.' end view = CursorCommandView.new(self, ) cursor = Cursor.new(view, result, server, session: session, context: context) ensure # If the cursor was created it owns the session and connection; # otherwise (error or no cursor in the response) release them here. unless cursor connection.connection_pool.check_in(connection) if connection && !connection.pinned? session.end_session if session && session.implicit? end end cursor end
#drop(options = {}) ⇒ Result
Drop the database and all its associated information.
# File 'lib/mongo/database.rb', line 439
def drop( = {}) operation = { dropDatabase: 1 } client.with_session() do |session| write_concern = if [:write_concern] WriteConcern.get([:write_concern]) else self.write_concern end Operation::DropDatabase.new({ selector: operation, db_name: name, write_concern: write_concern, session: session }).execute( next_primary(nil, session), context: Operation::Context.new( client: client, session: session, operation_timeouts: operation_timeouts() ) ) end end
#extract_cursor_command_view_options(options) ⇒ Hash (private)
Removes the getMore and cursor options from the options hash and returns
them as a separate hash for the Database::CursorCommandView. The remaining options
(e.g. :session, :read, :timeout_ms) are left for command execution.
# File 'lib/mongo/database.rb', line 697
def () %i[ batch_size max_time_ms comment cursor_type timeout_mode ].each_with_object({}) do |key, | [key] = .delete(key) if .key?(key) end end
#fs(options = {}) ⇒ Grid::FSBucket
Get the Grid "filesystem" for this database.
#inspect ⇒ String
Get a pretty printed string inspection for the database.
# File 'lib/mongo/database.rb', line 498
def inspect "#<Mongo::Database:0x#{object_id} name=#{name}>" end
#list_collections(options = {}) ⇒ Array<Hash>
The set of collections returned, and the schema of the information hash per collection, depends on the MongoDB server version that fulfills the request.
Get info on all the non-system collections in the database.
See https://mongodb.com/docs/manual/reference/command/listCollections/
for more information and usage.
# File 'lib/mongo/database.rb', line 178
def list_collections( = {}) View.new(self, ).list_collections() end
#operation_timeouts(opts) ⇒ Hash
# File 'lib/mongo/database.rb', line 677
def operation_timeouts(opts) # TODO: We should re-evaluate if we need two timeouts separately. {}.tap do |result| if opts[:timeout_ms].nil? result[:inherited_timeout_ms] = timeout_ms else result[:operation_timeout_ms] = opts.delete(:timeout_ms) end end end
#read_command(operation, opts = {}) ⇒ Hash
Execute a read command on the database, retrying the read if necessary.
# File 'lib/mongo/database.rb', line 394
def read_command(operation, opts = {}) txn_read_pref = (opts[:session].txn_read_preference if opts[:session] && opts[:session].in_transaction?) txn_read_pref ||= opts[:read] || ServerSelector::PRIMARY Lint.validate_underscore_read_preference(txn_read_pref) preference = ServerSelector.get(txn_read_pref) client.with_session(opts) do |session| context = Operation::Context.new( client: client, session: session, operation_timeouts: operation_timeouts(opts) ) operation = Operation::Command.new( selector: operation.dup, db_name: name, read: preference, session: session, comment: opts[:comment] ) op_name = opts[:op_name] || 'command' tracer.trace_operation(operation, context, op_name: op_name) do read_with_retry(session, preference, context) do |server| operation.execute(server, context: context) end end end end
#timeout_ms ⇒ Integer | nil
# File 'lib/mongo/database.rb', line 669
def timeout_ms [:timeout_ms] || client.timeout_ms end
#users ⇒ View::User
Get the user view for this database.
#watch(pipeline = [], options = {}) ⇒ ChangeStream
A change stream only allows 'majority' read concern.
This helper method is preferable to running a raw aggregation with a $changeStream stage, for the purpose of supporting resumability.
Allows users to request that notifications are sent for all changes that occur in the client's database.
# File 'lib/mongo/database.rb', line 635
def watch(pipeline = [], = {}) = .dup [:cursor_type] = :tailable_await if [:max_await_time_ms] Mongo::Collection::View::ChangeStream.new( Mongo::Collection::View.new(collection("#{COMMAND}.aggregate"), {}, ), pipeline, Mongo::Collection::View::ChangeStream::DATABASE, ) end