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,
  :database,
  :heartbeat_frequency,
  :id_generator,
  :local_threshold,
  :logger,
  :max_pool_size,
  :max_read_retries,
  :min_pool_size,
  :monitoring,
  :password,
  :platform,
  :read,
  :read_retry_interval,
  :replica_set,
  :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
].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_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.

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

Yields:

  • (_self)

Yield Parameters:

  • _self (Mongo::Client)

    the object that the method was called on

Since:

  • 2.0.0



230
231
232
233
234
235
236
237
238
# File 'lib/mongo/client.rb', line 230

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



76
77
78
# File 'lib/mongo/client.rb', line 76

def cluster
  @cluster
end

#databaseMongo::Database (readonly)

Returns database The database the client is operating on.

Returns:

Since:

  • 2.0.0



79
80
81
# File 'lib/mongo/client.rb', line 79

def database
  @database
end

#optionsHash (readonly)

Returns options The configuration options.

Returns:

  • (Hash)

    options The configuration options.

Since:

  • 2.0.0



82
83
84
# File 'lib/mongo/client.rb', line 82

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



100
101
102
103
# File 'lib/mongo/client.rb', line 100

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



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

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



326
327
328
# File 'lib/mongo/client.rb', line 326

def close
  @cluster.disconnect! and true
end

#database_namesArray<String>

Get the names of all databases.

Examples:

Get the database names.

client.database_names

Returns:

  • (Array<String>)

    The names of the databases.

Since:

  • 2.0.5



350
351
352
# File 'lib/mongo/client.rb', line 350

def database_names
  list_databases.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



129
130
131
# File 'lib/mongo/client.rb', line 129

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



248
249
250
# File 'lib/mongo/client.rb', line 248

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

#list_databasesArray<Hash>

Get info for each database.

Examples:

Get the info for each database.

client.list_databases

Returns:

  • (Array<Hash>)

    The info for each database.

Since:

  • 2.0.5



362
363
364
# File 'lib/mongo/client.rb', line 362

def list_databases
  use(Database::ADMIN).command(listDatabases: 1).first[Database::DATABASES]
end

#read_preferenceObject

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

Examples:

Get the read preference.

client.read_preference

Returns:

  • (Object)

    The appropriate read preference or primary if none was provided to the client.

Since:

  • 2.0.0



261
262
263
# File 'lib/mongo/client.rb', line 261

def read_preference
  @read_preference ||= ServerSelector.get(options[:read] || ServerSelector::PRIMARY)
end

#reconnecttrue

Reconnect the client.

Examples:

Reconnect the client.

client.reconnect

Returns:

  • (true)

    Always true.

Since:

  • 2.1.0



338
339
340
# File 'lib/mongo/client.rb', line 338

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



276
277
278
# File 'lib/mongo/client.rb', line 276

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



292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/mongo/client.rb', line 292

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



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

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