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

[
  :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,
  :read,
  :read_retry_interval,
  :replica_set,
  :server_selection_timeout,
  :socket_timeout,
  :ssl,
  :ssl_ca_cert,
  :ssl_cert,
  :ssl_key,
  :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.

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

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

Yields:

  • (_self)

Yield Parameters:

  • _self (Mongo::Client)

    the object that the method was called on

Since:

  • 2.0.0



197
198
199
200
201
202
203
204
205
# File 'lib/mongo/client.rb', line 197

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



68
69
70
# File 'lib/mongo/client.rb', line 68

def cluster
  @cluster
end

#databaseMongo::Database (readonly)

Returns database The database the client is operating on.

Returns:

Since:

  • 2.0.0



71
72
73
# File 'lib/mongo/client.rb', line 71

def database
  @database
end

#optionsHash (readonly)

Returns options The configuration options.

Returns:

  • (Hash)

    options The configuration options.

Since:

  • 2.0.0



74
75
76
# File 'lib/mongo/client.rb', line 74

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



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

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



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

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



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

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



317
318
319
# File 'lib/mongo/client.rb', line 317

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



121
122
123
# File 'lib/mongo/client.rb', line 121

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



215
216
217
# File 'lib/mongo/client.rb', line 215

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



329
330
331
# File 'lib/mongo/client.rb', line 329

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



228
229
230
# File 'lib/mongo/client.rb', line 228

def read_preference
  @read_preference ||= ServerSelector.get(Options::Redacted.new(options[:read] || {}).merge(options))
end

#reconnecttrue

Reconnect the client.

Examples:

Reconnect the client.

client.reconnect

Returns:

  • (true)

    Always true.

Since:

  • 2.1.0



305
306
307
# File 'lib/mongo/client.rb', line 305

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



243
244
245
# File 'lib/mongo/client.rb', line 243

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



259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/mongo/client.rb', line 259

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



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

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