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

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_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' ])

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

  • :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. They consist of a mode specified as a symbol, an array of hashes known as tag_sets, and local_threshold. :mode can be one of :secondary, :secondary_preferred, :primary, :primary_preferred, :nearest.

  • :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 or not to do peer certification validation.

  • :ssl_ca_cert (String)

    The file containing a set of concatenated certification authority certifications 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 a set of concatenated certification authority certifications 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 certification authority certifications 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.

  • :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.

Yields:

  • (_self)

Yield Parameters:

  • _self (Mongo::Client)

    the object that the method was called on

Since:

  • 2.0.0



248
249
250
251
252
253
254
255
256
# File 'lib/mongo/client.rb', line 248

def initialize(addresses_or_uri, options = Options::Redacted.new)
  @monitoring = Monitoring.new(options)
  if addresses_or_uri.is_a?(::String)
    create_from_uri(addresses_or_uri, validate_options!(options))
  else
    create_from_addresses(addresses_or_uri, validate_options!(options))
  end
  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



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

def cluster
  @cluster
end

#databaseMongo::Database (readonly)

Returns database The database the client is operating on.

Returns:

Since:

  • 2.0.0



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

def database
  @database
end

#optionsHash (readonly)

Returns options The configuration options.

Returns:

  • (Hash)

    options The configuration options.

Since:

  • 2.0.0



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

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



109
110
111
112
# File 'lib/mongo/client.rb', line 109

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



126
127
128
# File 'lib/mongo/client.rb', line 126

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



357
358
359
# File 'lib/mongo/client.rb', line 357

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



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

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



138
139
140
# File 'lib/mongo/client.rb', line 138

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



266
267
268
# File 'lib/mongo/client.rb', line 266

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



400
401
402
403
404
405
# File 'lib/mongo/client.rb', line 400

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



418
419
420
421
422
# File 'lib/mongo/client.rb', line 418

def list_mongo_databases(filter = {}, opts = {})
  database_names(filter, opts).collect do |name|
    Database.new(self, name, options)
  end
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.

Since:

  • 2.0.0



292
293
294
# File 'lib/mongo/client.rb', line 292

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



369
370
371
# File 'lib/mongo/client.rb', line 369

def reconnect
  @cluster.reconnect! and 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



280
281
282
# File 'lib/mongo/client.rb', line 280

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



437
438
439
440
# File 'lib/mongo/client.rb', line 437

def start_session(options = {})
  cluster.send(:get_session, 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



307
308
309
# File 'lib/mongo/client.rb', line 307

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



323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/mongo/client.rb', line 323

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



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

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