Class: Mongo::Database

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Retryable
Defined in:
build/ruby-driver-master/lib/mongo/database.rb,
build/ruby-driver-master/lib/mongo/database/view.rb

Overview

Represents a database on the db server and operations that can execute on it at this level.

Since:

  • 2.0.0

Defined Under Namespace

Classes: View

Constant Summary collapse

ADMIN =

The admin database name.

Since:

  • 2.0.0

'admin'.freeze
COMMAND =

The “collection” that database commands operate against.

Since:

  • 2.0.0

'$cmd'.freeze
DEFAULT_OPTIONS =

The default database options.

Since:

  • 2.0.0

Options::Redacted.new(:database => ADMIN).freeze
NAME =
Deprecated.

Database name field constant.

Since:

  • 2.1.0

'name'.freeze
DATABASES =

Databases constant.

Since:

  • 2.1.0

'databases'.freeze
NAMESPACES =

The name of the collection that holds all the collection names.

Since:

  • 2.0.0

'system.namespaces'.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Retryable

#legacy_write_with_retry, #nro_write_with_retry, #read_with_one_retry, #read_with_retry, #read_with_retry_cursor, #write_with_retry

Constructor Details

#initialize(client, name, options = {}) ⇒ Database

Instantiate a new database object.

Examples:

Instantiate the database.

Mongo::Database.new(client, :test)

Parameters:

  • client (Mongo::Client)

    The driver client.

  • name (String, Symbol)

    The name of the database.

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

    The options.

Raises:

  • (Mongo::Database::InvalidName)

    If the name is nil.

Since:

  • 2.0.0



308
309
310
311
312
313
314
315
316
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 308

def initialize(client, name, options = {})
  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 = options.freeze
end

Instance Attribute Details

#clientClient (readonly)

Returns client The database client.

Returns:

  • (Client)

    client The database client.

Since:

  • 2.0.0



62
63
64
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 62

def client
  @client
end

#nameString (readonly)

Returns name The name of the database.

Returns:

  • (String)

    name The name of the database.

Since:

  • 2.0.0



65
66
67
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 65

def name
  @name
end

#optionsHash (readonly)

Returns options The options.

Returns:

  • (Hash)

    options The options.

Since:

  • 2.0.0



68
69
70
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 68

def options
  @options
end

Class Method Details

.create(client) ⇒ Database

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Create a database for the provided client, for use when we don't want the client's original database instance to be the same.

Examples:

Create a database for the client.

Database.create(client)

Parameters:

  • client (Client)

    The client to create on.

Returns:

Since:

  • 2.0.0



452
453
454
455
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 452

def self.create(client)
  database = Database.new(client, client.options[:database], client.options)
  client.instance_variable_set(:@database, database)
end

Instance Method Details

#==(other) ⇒ true, false

Check equality of the database object against another. Will simply check if the names are the same.

Examples:

Check database equality.

database == other

Parameters:

  • other (Object)

    The object to check against.

Returns:

  • (true, false)

    If the objects are equal.

Since:

  • 2.0.0



93
94
95
96
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 93

def ==(other)
  return false unless other.is_a?(Database)
  name == other.name
end

#[](collection_name, options = {}) ⇒ Mongo::Collection Also known as: collection

Get a collection in this database by the provided name.

Examples:

Get a collection.

database[:users]

Parameters:

  • collection_name (String, Symbol)

    The name of the collection.

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

    The options to the collection.

Returns:

Since:

  • 2.0.0



109
110
111
112
113
114
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 109

def [](collection_name, options = {})
  if options[: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, options)
end

#aggregate(pipeline, options = {}) ⇒ Aggregation

Perform an aggregation on the database.

Examples:

Perform an aggregation.

collection.aggregate([ { "$listLocalSessions" => {} } ])

Parameters:

  • pipeline (Array<Hash>)

    The aggregation pipeline.

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

    The aggregation options.

Options Hash (options):

  • :allow_disk_use (true, false)

    Set to true if disk usage is allowed during the aggregation.

  • :batch_size (Integer)

    The number of documents to return per batch.

  • :bypass_document_validation (true, false)

    Whether or not to skip document level validation.

  • :collation (Hash)

    The collation to use.

  • :comment (String)

    Associate a comment with the aggregation.

  • :hint (String)

    The index to use for the aggregation.

  • :max_time_ms (Integer)

    The maximum amount of time in milliseconds to allow the aggregation to run.

  • :use_cursor (true, false)

    Indicates whether the command will request that the server provide results using a cursor. Note that as of server version 3.6, aggregations always provide results using a cursor and this option is therefore not valid.

  • :session (Session)

    The session to use.

Returns:

  • (Aggregation)

    The aggregation object.

Since:

  • 2.10.0



394
395
396
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 394

def aggregate(pipeline, options = {})
  View.new(self).aggregate(pipeline, options)
end

#clusterMongo::Server

Returns Get the primary server from the cluster.

Returns:

Since:

  • 2.0.0



79
80
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 79

def_delegators :cluster,
:next_primary

#collection_names(options = {}) ⇒ Array<String>

Note:

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.

Parameters:

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

Options Hash (options):

  • :filter (Hash)

    A filter on the collections returned.

  • :authorized_collections (true, false)

    A flag, when set to true and used with nameOnly: true, that allows a user without the required privilege to run the command when access control is enforced

    See docs.mongodb.com/manual/reference/command/listCollections/ for more information and usage.

Returns:

  • (Array<String>)

    Names of the collections.

Since:

  • 2.0.0



135
136
137
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 135

def collection_names(options = {})
  View.new(self).collection_names(options)
end

#collections(options = {}) ⇒ Array<Mongo::Collection>

Note:

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.

Parameters:

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

Options Hash (options):

  • :filter (Hash)

    A filter on the collections returned.

  • :authorized_collections (true, false)

    A flag, when set to true and used with name_only: true, that allows a user without the required privilege to run the command when access control is enforced

    See docs.mongodb.com/manual/reference/command/listCollections/ for more information and usage.

Returns:

Since:

  • 2.0.0



184
185
186
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 184

def collections(options = {})
  collection_names(options).map { |name| collection(name) }
end

#command(operation, opts = {}) ⇒ Mongo::Operation::Result

Execute a command on the database.

Examples:

Execute a command.

database.command(:hello => 1)

Parameters:

  • operation (Hash)

    The command to execute.

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

    The command options.

Options Hash (opts):

  • :read (Hash)

    The read preference for this command.

  • :session (Session)

    The session to use for this command.

  • :execution_options (Hash)

    Options to pass to the code that executes this command. This is an internal option and is subject to change.

    • :deserialize_as_bson [ Boolean ] Whether to deserialize the response to this command using BSON types intead of native Ruby types wherever possible.

Returns:

Since:

  • 2.0.0



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 206

def command(operation, opts = {})
  opts = opts.dup
  execution_opts = opts.delete(:execution_options) || {}

  txn_read_pref = if opts[:session] && opts[:session].in_transaction?
    opts[:session].txn_read_preference
  else
    nil
  end
  txn_read_pref ||= opts[:read] || ServerSelector::PRIMARY
  Lint.validate_underscore_read_preference(txn_read_pref)
  selector = ServerSelector.get(txn_read_pref)

  client.send(:with_session, opts) do |session|
    server = selector.select_server(cluster, nil, session)
    op = Operation::Command.new(
      :selector => operation.dup,
      :db_name => name,
      :read => selector,
      :session => session
    )

    op.execute(server,
      context: Operation::Context.new(client: client, session: session),
      options: execution_opts)
  end
end

#drop(options = {}) ⇒ Result

Drop the database and all its associated information.

Examples:

Drop the database.

database.drop

Parameters:

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

    The options for the operation.

  • opts (Hash)

    a customizable set of options

Options Hash (options):

  • :session (Session)

    The session to use for the operation.

Returns:

  • (Result)

    The result of the command.

Since:

  • 2.0.0



279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 279

def drop(options = {})
  operation = { :dropDatabase => 1 }
  client.send(:with_session, options) do |session|
    write_concern = if options[:write_concern]
      WriteConcern.get(options[: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))
  end
end

#fs(options = {}) ⇒ Grid::FSBucket

Get the Grid “filesystem” for this database.

Parameters:

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

    The GridFS options.

Options Hash (options):

  • :bucket_name (String)

    The prefix for the files and chunks collections.

  • :chunk_size (Integer)

    Override the default chunk size.

  • :fs_name (String)

    The prefix for the files and chunks collections.

  • :read (String)

    The read preference.

  • :session (Session)

    The session to use.

  • :write (Hash)

    Deprecated. Equivalent to :write_concern option.

  • :write_concern (Hash)

    The write concern options. Can be :w => Integer|String, :fsync => Boolean, :j => Boolean.

Returns:

Since:

  • 2.0.0



350
351
352
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 350

def fs(options = {})
  Grid::FSBucket.new(self, options)
end

#inspectString

Get a pretty printed string inspection for the database.

Examples:

Inspect the database.

database.inspect

Returns:

  • (String)

    The database inspection.

Since:

  • 2.0.0



326
327
328
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 326

def inspect
  "#<Mongo::Database:0x#{object_id} name=#{name}>"
end

#list_collections(options = {}) ⇒ Array<Hash>

Note:

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.

Parameters:

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

Options Hash (options):

  • :filter (Hash)

    A filter on the collections returned.

  • :name_only (true, false)

    Indicates whether command should return just collection/view names and type or return both the name and other information

  • :authorized_collections (true, false)

    A flag, when set to true and used with nameOnly: true, that allows a user without the required privilege to run the command when access control is enforced

    See docs.mongodb.com/manual/reference/command/listCollections/ for more information and usage.

Returns:

  • (Array<Hash>)

    Array of information hashes, one for each collection in the database.

Since:

  • 2.0.5



162
163
164
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 162

def list_collections(options = {})
  View.new(self).list_collections(options)
end

#read_command(operation, opts = {}) ⇒ Hash

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Execute a read command on the database, retrying the read if necessary.

Parameters:

  • operation (Hash)

    The command to execute.

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

    The command options.

Options Hash (opts):

  • :read (Hash)

    The read preference for this command.

  • :session (Session)

    The session to use for this command.

Returns:

  • (Hash)

    The result of the command execution.

Since:

  • 2.0.0



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 244

def read_command(operation, opts = {})
  txn_read_pref = if opts[:session] && opts[:session].in_transaction?
    opts[:session].txn_read_preference
  else
    nil
  end
  txn_read_pref ||= opts[:read] || ServerSelector::PRIMARY
  Lint.validate_underscore_read_preference(txn_read_pref)
  preference = ServerSelector.get(txn_read_pref)

  client.send(:with_session, opts) do |session|
    read_with_retry(session, preference) do |server|
      Operation::Command.new(
        selector: operation.dup,
        db_name: name,
        read: preference,
        session: session,
      ).execute(server, context: Operation::Context.new(client: client, session: session))
    end
  end
end

#usersView::User

Get the user view for this database.

Examples:

Get the user view.

database.users

Returns:

  • (View::User)

    The user view.

Since:

  • 2.0.0



362
363
364
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 362

def users
  Auth::User::View.new(self)
end

#watch(pipeline = [], options = {}) ⇒ ChangeStream

Note:

A change stream only allows 'majority' read concern.

Note:

This helper method is preferable to running a raw aggregation with a $changeStream stage, for the purpose of supporting resumability.

As of version 3.6 of the MongoDB server, a “$changeStream“ pipeline stage is supported in the aggregation framework. As of version 4.0, this stage allows users to request that notifications are sent for all changes that occur in the client's database.

Examples:

Get change notifications for a given database..

database.watch([{ '$match' => { operationType: { '$in' => ['insert', 'replace'] } } }])

Parameters:

  • pipeline (Array<Hash>) (defaults to: [])

    Optional additional filter operators.

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

    The change stream options.

Options Hash (options):

  • :full_document (String)

    Allowed values: 'default', 'updateLookup'. Defaults to 'default'. When set to 'updateLookup', the change notification for partial updates will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.

  • :resume_after (BSON::Document, Hash)

    Specifies the logical starting point for the new change stream.

  • :max_await_time_ms (Integer)

    The maximum amount of time for the server to wait on new documents to satisfy a change stream query.

  • :batch_size (Integer)

    The number of documents to return per batch.

  • :collation (BSON::Document, Hash)

    The collation to use.

  • :session (Session)

    The session to use.

  • :start_at_operation_time (BSON::Timestamp)

    Only return changes that occurred after the specified timestamp. Any command run against the server will return a cluster time that can be used here. Only recognized by server versions 4.0+.

Returns:

  • (ChangeStream)

    The change stream object.

Since:

  • 2.6.0



431
432
433
434
435
436
437
# File 'build/ruby-driver-master/lib/mongo/database.rb', line 431

def watch(pipeline = [], options = {})
  Mongo::Collection::View::ChangeStream.new(
    Mongo::Collection::View.new(collection("#{COMMAND}.aggregate")),
    pipeline,
    Mongo::Collection::View::ChangeStream::DATABASE,
    options)
end