Class: Mongo::Client

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Loggable
Defined in:
lib/mongo/client.rb

Overview

The client is the entry point to the driver and is the main object that will be interacted with.

Since:

  • 2.0.0

Constant Summary collapse

CRUD_OPTIONS =

The options that do not affect the behaviour of a cluster and its subcomponents.

Since:

  • 2.1.0

[ :database, :read, :write ].freeze
VALID_OPTIONS =

Valid client options.

Since:

  • 2.1.2

[
  :app_name,
  :auth_mech,
  :auth_mech_properties,
  :auth_source,
  :connect,
  :connect_timeout,
  :compressors,
  :database,
  :heartbeat_frequency,
  :id_generator,
  :local_threshold,
  :logger,
  :max_idle_time,
  :max_pool_size,
  :max_read_retries,
  :min_pool_size,
  :monitoring,
  :password,
  :platform,
  :read,
  :read_concern,
  :read_retry_interval,
  :replica_set,
  :retry_writes,
  :server_selection_timeout,
  :socket_timeout,
  :ssl,
  :ssl_ca_cert,
  :ssl_ca_cert_string,
  :ssl_ca_cert_object,
  :ssl_cert,
  :ssl_cert_string,
  :ssl_cert_object,
  :ssl_key,
  :ssl_key_string,
  :ssl_key_object,
  :ssl_key_pass_phrase,
  :ssl_verify,
  :truncate_logs,
  :user,
  :wait_queue_timeout,
  :write,
  :zlib_compression_level
].freeze
VALID_COMPRESSORS =

The compression algorithms supported by the driver.

Since:

  • 2.5.0

[ Mongo::Protocol::Compressed::ZLIB ].freeze

Constants included from Loggable

Loggable::PREFIX

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Loggable

#log_debug, #log_error, #log_fatal, #log_info, #log_warn, #logger

Constructor Details

#initialize(addresses_or_uri, options = Options::Redacted.new) {|_self| ... } ⇒ Client

Instantiate a new driver client.

Examples:

Instantiate a single server or mongos client.

Mongo::Client.new(['127.0.0.1:27017'])

Instantiate a client for a replica set.

Mongo::Client.new(['127.0.0.1:27017', '127.0.0.1:27021'])

Directly connect to a mongod in a replica set

Mongo::Client.new(['127.0.0.1:27017'], :connect => :direct)
# without `:connect => :direct`, Mongo::Client will discover and
# connect to the replica set if given the address of a server in
# a replica set

Parameters:

  • addresses_or_uri (Array<String>, String)

    The array of server addresses in the form of host:port or a MongoDB URI connection string.

  • options (Hash) (defaults to: Options::Redacted.new)

    The options to be used by the client.

Options Hash (options):

  • :auth_mech (Symbol)

    The authentication mechanism to use. One of :mongodb_cr, :mongodb_x509, :plain, :scram, :scram256

  • :auth_source (String)

    The source to authenticate from.

  • :connect (Symbol)

    The connection method to use. This forces the cluster to behave in the specified way instead of auto-discovering. One of :direct, :replica_set, :sharded

  • :database (String)

    The database to connect to.

  • :auth_mech_properties (Hash)
  • :heartbeat_frequency (Float)

    The number of seconds for the server monitor to refresh it's description via ismaster.

  • :local_threshold (Integer)

    The local threshold boundary in seconds for selecting a near server for an operation.

  • :server_selection_timeout (Integer)

    The timeout in seconds for selecting a server for an operation.

  • :password (String)

    The user's password.

  • :max_idle_time (Integer)

    The maximum seconds a socket can remain idle since it has been checked in to the pool.

  • :max_pool_size (Integer)

    The maximum size of the connection pool.

  • :min_pool_size (Integer)

    The minimum size of the connection pool.

  • :wait_queue_timeout (Float)

    The time to wait, in seconds, in the connection pool for a connection to be checked in.

  • :connect_timeout (Float)

    The timeout, in seconds, to attempt a connection.

  • :compressors (Array<String>)

    A list of potential compressors to use, in order of preference. The driver chooses the first compressor that is also supported by the server. Currently the driver only supports 'zlib'.

  • :read (Hash)

    The read preference options. The hash may have the following items:

    • :mode – read preference specified as a symbol; valid values are :primary, :primary_preferred, :secondary, :secondary_preferred and :nearest.

    • :tag_sets – an array of hashes.

    • :local_threshold.

  • :replica_set (Symbol)

    The name of the replica set to connect to. Servers not in this replica set will be ignored.

  • :ssl (true, false)

    Whether to use SSL.

  • :ssl_cert (String)

    The certificate file used to identify the connection against MongoDB. This option, if present, takes precedence over the values of :ssl_cert_string and :ssl_cert_object

  • :ssl_cert_string (String)

    A string containing the PEM-encoded certificate used to identify the connection against MongoDB. This option, if present, takes precedence over the value of :ssl_cert_object

  • :ssl_cert_object (OpenSSL::X509::Certificate)

    The OpenSSL::X509::Certificate used to identify the connection against MongoDB

  • :ssl_key (String)

    The private keyfile used to identify the connection against MongoDB. Note that even if the key is stored in the same file as the certificate, both need to be explicitly specified. This option, if present, takes precedence over the values of :ssl_key_string and :ssl_key_object

  • :ssl_key_string (String)

    A string containing the PEM-encoded private key used to identify the connection against MongoDB. This parameter, if present, takes precedence over the value of option :ssl_key_object

  • :ssl_key_object (OpenSSL::PKey)

    The private key used to identify the connection against MongoDB

  • :ssl_key_pass_phrase (String)

    A passphrase for the private key.

  • :ssl_verify (true, false)

    Whether to do peer certificate validation.

  • :ssl_ca_cert (String)

    The file containing concatenated certificate authority certificates used to validate certs passed from the other end of the connection. One of :ssl_ca_cert, :ssl_ca_cert_string or :ssl_ca_cert_object (in order of priority) is required for :ssl_verify.

  • :ssl_ca_cert_string (String)

    A string containing concatenated certificate authority certificates used to validate certs passed from the other end of the connection. One of :ssl_ca_cert, :ssl_ca_cert_string or :ssl_ca_cert_object (in order of priority) is required for :ssl_verify.

  • :ssl_ca_cert_object (Array<OpenSSL::X509::Certificate>)

    An array of OpenSSL::X509::Certificate representing the certificate authority certificates used to validate certs passed from the other end of the connection. One of :ssl_ca_cert, :ssl_ca_cert_string or :ssl_ca_cert_object (in order of priority) is required for :ssl_verify.

  • :socket_timeout (Float)

    The timeout, in seconds, to execute operations on a socket.

  • :user (String)

    The user name.

  • :write (Hash)

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

  • :read_concern (Hash)

    The read concern option.

  • :monitoring (true, false)

    Initializes a client without any default monitoring if false is provided.

  • :logger (Logger)

    A custom logger if desired.

  • :truncate_logs (true, false)

    Whether to truncate the logs at the default 250 characters.

  • :max_read_retries (Integer)

    The maximum number of read retries on mongos query failures.

  • :read_retry_interval (Float)

    The interval, in seconds, in which reads on a mongos are retried.

  • :id_generator (Object)

    A custom object to generate ids for documents. Must respond to #generate.

  • :app_name (String, Symbol)

    Application name that is printed to the mongod logs upon establishing a connection in server versions >= 3.4.

  • :platform (String)

    Platform information to include in the metadata printed to the mongod logs upon establishing a connection in server versions >= 3.4.

  • :zlib_compression_level (Integer)

    The Zlib compression level to use, if using compression. See Ruby's Zlib module for valid levels.

  • :retry_writes (true, false)

    Retry writes once when connected to a replica set or sharded cluster versions 3.6 and up.

  • :sdam_proc (Proc)

    A Proc to invoke with the client as the argument prior to performing server discovery and monitoring. Use this to set up SDAM event listeners to receive events dispatched during client construction.

Yields:

  • (_self)

Yield Parameters:

  • _self (Mongo::Client)

    the object that the method was called on

Since:

  • 2.0.0



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/mongo/client.rb', line 267

def initialize(addresses_or_uri, options = Options::Redacted.new)
  Mongo::Lint.validate_underscore_read_preference(options[:read])
  if addresses_or_uri.is_a?(::String)
    uri = URI.get(addresses_or_uri, options)
    addresses = uri.servers
    options = uri.client_options.merge(options)
  else
    addresses = addresses_or_uri
  end
  options = options.dup
  # Special handling for sdam_proc as it is only used during client
  # construction
  sdam_proc = options.delete(:sdam_proc)
  @options = validate_options!(Database::DEFAULT_OPTIONS.merge(options)).freeze
  @database = Database.new(self, @options[:database], @options)
  monitoring = Monitoring.new(@options)
  if sdam_proc
    @cluster = Cluster.new([], monitoring, @options)
    sdam_proc.call(self)
  end
  @cluster = Cluster.new(addresses, monitoring, @options)
  yield(self) if block_given?
end

Instance Attribute Details

#clusterMongo::Cluster (readonly)

Returns cluster The cluster of servers for the client.

Returns:

Since:

  • 2.0.0



86
87
88
# File 'lib/mongo/client.rb', line 86

def cluster
  @cluster
end

#databaseMongo::Database (readonly)

Returns database The database the client is operating on.

Returns:

Since:

  • 2.0.0



89
90
91
# File 'lib/mongo/client.rb', line 89

def database
  @database
end

#optionsHash (readonly)

Returns options The configuration options.

Returns:

  • (Hash)

    options The configuration options.

Since:

  • 2.0.0



92
93
94
# File 'lib/mongo/client.rb', line 92

def options
  @options
end

Instance Method Details

#==(other) ⇒ true, false Also known as: eql?

Determine if this client is equivalent to another object.

Examples:

Check client equality.

client == other

Parameters:

  • other (Object)

    The object to compare to.

Returns:

  • (true, false)

    If the objects are equal.

Since:

  • 2.0.0



115
116
117
118
# File 'lib/mongo/client.rb', line 115

def ==(other)
  return false unless other.is_a?(Client)
  cluster == other.cluster && options == other.options
end

#[](collection_name, options = {}) ⇒ Mongo::Collection

Get a collection object for the provided collection name.

Examples:

Get the collection.

client[: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



132
133
134
# File 'lib/mongo/client.rb', line 132

def [](collection_name, options = {})
  database[collection_name, options]
end

#closetrue

Close all connections.

Examples:

Disconnect the client.

client.close

Returns:

  • (true)

    Always true.

Since:

  • 2.1.0



409
410
411
# File 'lib/mongo/client.rb', line 409

def close
  @cluster.disconnect! and true
end

#database_names(filter = {}, opts = {}) ⇒ Array<String>

Get the names of all databases.

Examples:

Get the database names.

client.database_names

Parameters:

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

    The filter criteria for getting a list of databases.

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

    The command options.

Returns:

  • (Array<String>)

    The names of the databases.

Since:

  • 2.0.5



442
443
444
# File 'lib/mongo/client.rb', line 442

def database_names(filter = {}, opts = {})
  list_databases(filter, true, opts).collect{ |info| info[Database::NAME] }
end

#hashInteger

Get the hash value of the client.

Examples:

Get the client hash value.

client.hash

Returns:

  • (Integer)

    The client hash value.

Since:

  • 2.0.0



144
145
146
# File 'lib/mongo/client.rb', line 144

def hash
  [cluster, options].hash
end

#inspectString

Get an inspection of the client as a string.

Examples:

Inspect the client.

client.inspect

Returns:

  • (String)

    The inspection string.

Since:

  • 2.0.0



299
300
301
# File 'lib/mongo/client.rb', line 299

def inspect
  "#<Mongo::Client:0x#{object_id} cluster=#{cluster.addresses.join(', ')}>"
end

#list_databases(filter = {}, name_only = false, opts = {}) ⇒ Array<Hash>

Get info for each database.

Examples:

Get the info for each database.

client.list_databases

Parameters:

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

    The filter criteria for getting a list of databases.

  • name_only (true, false) (defaults to: false)

    Whether to only return each database name without full metadata.

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

    The command options.

Returns:

  • (Array<Hash>)

    The info for each database.

Since:

  • 2.0.5



458
459
460
461
462
463
# File 'lib/mongo/client.rb', line 458

def list_databases(filter = {}, name_only = false, opts = {})
  cmd = { listDatabases: 1 }
  cmd[:nameOnly] = !!name_only
  cmd[:filter] = filter unless filter.empty?
  use(Database::ADMIN).command(cmd, opts).first[Database::DATABASES]
end

#list_mongo_databases(filter = {}, opts = {}) ⇒ Array<Mongo::Database>

Returns a list of Mongo::Database objects.

Examples:

Get a list of Mongo::Database objects.

client.list_mongo_databases

Parameters:

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

    The filter criteria for getting a list of databases.

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

    The command options.

Returns:

Since:

  • 2.5.0



476
477
478
479
480
# File 'lib/mongo/client.rb', line 476

def list_mongo_databases(filter = {}, opts = {})
  database_names(filter, opts).collect do |name|
    Database.new(self, name, options)
  end
end

#read_concernHash

Get the read concern for this client.

Examples:

Get the client read concern.

client.read_concern

Returns:

  • (Hash)

    The read concern.

Since:

  • 2.6.0



383
384
385
# File 'lib/mongo/client.rb', line 383

def read_concern
  @read_concern ||= options[:read_concern]
end

#read_preferenceBSON::Document

Get the read preference from the options passed to the client.

Examples:

Get the read preference.

client.read_preference

Returns:

  • (BSON::Document)

    The user-defined read preference. The document may have the following fields:

    • :read – read preference specified as a symbol; valid values are :primary, :primary_preferred, :secondary, :secondary_preferred and :nearest.

    • :tag_sets – an array of hashes.

    • :local_threshold.

Since:

  • 2.0.0



331
332
333
# File 'lib/mongo/client.rb', line 331

def read_preference
  @read_preference ||= options[:read]
end

#reconnecttrue

Reconnect the client.

Examples:

Reconnect the client.

client.reconnect

Returns:

  • (true)

    Always true.

Since:

  • 2.1.0



421
422
423
424
425
426
427
428
429
# File 'lib/mongo/client.rb', line 421

def reconnect
  addresses = cluster.addresses.map(&:to_s)
  monitoring = cluster.monitoring

  @cluster.disconnect! rescue nil

  @cluster = Cluster.new(addresses, monitoring, options)
  true
end

#server_selectorMongo::ServerSelector

Get the server selector. It either uses the read preference defined in the client options or defaults to a Primary server selector.

Examples:

Get the server selector.

client.server_selector

Returns:

  • (Mongo::ServerSelector)

    The server selector using the user-defined read preference or a Primary server selector default.

Since:

  • 2.5.0



313
314
315
# File 'lib/mongo/client.rb', line 313

def server_selector
  @server_selector ||= ServerSelector.get(read_preference || ServerSelector::PRIMARY)
end

#start_session(options = {}) ⇒ Session

Note:

A Session cannot be used by multiple threads at once; session objects are not thread-safe.

Start a session.

Examples:

Start a session.

client.start_session(causal_consistency: true)

Parameters:

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

    The session options.

Returns:

Since:

  • 2.5.0



495
496
497
498
# File 'lib/mongo/client.rb', line 495

def start_session(options = {})
  cluster.send(:get_session, self, options.merge(implicit: false)) ||
    (raise Error::InvalidSession.new(Session::SESSIONS_NOT_SUPPORTED))
end

#use(name) ⇒ Mongo::Client

Use the database with the provided name. This will switch the current database the client is operating on.

Examples:

Use the provided database.

client.use(:users)

Parameters:

  • name (String, Symbol)

    The name of the database to use.

Returns:

Since:

  • 2.0.0



346
347
348
# File 'lib/mongo/client.rb', line 346

def use(name)
  with(database: name)
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 cluster.

Examples:

Get change notifications for the client's cluster.

client.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 at or 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



533
534
535
536
537
538
539
540
541
# File 'lib/mongo/client.rb', line 533

def watch(pipeline = [], options = {})
  return use(Database::ADMIN).watch(pipeline, options) unless database.name == Database::ADMIN

  Mongo::Collection::View::ChangeStream.new(
    Mongo::Collection::View.new(self["#{Database::COMMAND}.aggregate"]),
    pipeline,
    Mongo::Collection::View::ChangeStream::CLUSTER,
    options)
end

#with(new_options = Options::Redacted.new) ⇒ Mongo::Client

Provides a new client with the passed options merged over the existing options of this client. Useful for one-offs to change specific options without altering the original client.

Examples:

Get a client with changed options.

client.with(:read => { :mode => :primary_preferred })

Parameters:

  • new_options (Hash) (defaults to: Options::Redacted.new)

    The new options to use.

Returns:

Since:

  • 2.0.0



362
363
364
365
366
367
368
369
370
371
372
373
# File 'lib/mongo/client.rb', line 362

def with(new_options = Options::Redacted.new)
  clone.tap do |client|
    opts = validate_options!(new_options)
    client.options.update(opts)
    Database.create(client)
    # We can't use the same cluster if some options that would affect it
    # have changed.
    if cluster_modifying?(opts)
      Cluster.create(client)
    end
  end
end

#write_concernMongo::WriteConcern

Get the write concern for this client. If no option was provided, then a default single server acknowledgement will be used.

Examples:

Get the client write concern.

client.write_concern

Returns:

Since:

  • 2.0.0



397
398
399
# File 'lib/mongo/client.rb', line 397

def write_concern
  @write_concern ||= WriteConcern.get(options[:write])
end