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 behavior of a cluster and its subcomponents.

Since:

  • 2.1.0

[
  :auto_encryption_options,
  :database,
  :read, :read_concern,
  :write, :write_concern,
  :retry_reads, :max_read_retries, :read_retry_interval,
  :retry_writes, :max_write_retries,
  :max_adaptive_retries, :enable_overload_retargeting,
  :timeout_ms,

  # Options which cannot currently be here:
  #
  # :server_selection_timeout
  # Server selection timeout is used by cluster constructor to figure out
  # how long to wait for initial scan in compatibility mode, but once
  # the cluster is initialized it no longer uses this timeout.
  # Unfortunately server selector reads server selection timeout out of
  # the cluster, and this behavior is required by Cluster#next_primary
  # which takes no arguments. When next_primary is removed we can revisit
  # using the same cluster object with different server selection timeouts.
].freeze
VALID_OPTIONS =

Valid client options.

Since:

  • 2.1.2

%i[
  app_name
  auth_mech
  auth_mech_properties
  auth_source
  auto_encryption_options
  bg_error_backtrace
  cleanup
  compressors
  direct_connection
  enable_overload_retargeting
  connect
  connect_timeout
  database
  heartbeat_frequency
  id_generator
  load_balanced
  local_threshold
  logger
  log_prefix
  max_adaptive_retries
  max_connecting
  max_idle_time
  max_pool_size
  max_read_retries
  max_write_retries
  min_pool_size
  monitoring
  monitoring_io
  password
  platform
  populator_io
  read
  read_concern
  read_retry_interval
  replica_set
  resolv_options
  retry_reads
  retry_writes
  scan
  sdam_proc
  server_api
  server_monitoring_mode
  server_selection_timeout
  socket_timeout
  srv_max_hosts
  srv_service_name
  ssl
  ssl_ca_cert
  ssl_ca_cert_object
  ssl_ca_cert_string
  ssl_cert
  ssl_cert_object
  ssl_cert_string
  ssl_key
  ssl_key_object
  ssl_key_pass_phrase
  ssl_key_string
  ssl_verify
  ssl_verify_certificate
  ssl_verify_hostname
  ssl_verify_ocsp_endpoint
  timeout_ms
  tracing
  truncate_logs
  user
  wait_queue_timeout
  wrapping_libraries
  write
  write_concern
  zlib_compression_level
].freeze
VALID_COMPRESSORS =

The compression algorithms supported by the driver.

Since:

  • 2.5.0

[
  Mongo::Protocol::Compressed::ZSTD,
  Mongo::Protocol::Compressed::SNAPPY,
  Mongo::Protocol::Compressed::ZLIB
].freeze
VALID_SERVER_API_VERSIONS =

The known server API versions.

Since:

  • 2.0.0

%w[
  1
].freeze

Constants included from Loggable

Loggable::PREFIX

Instance Attribute Summary collapse

Class Method 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 = nil) ⇒ 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: nil)

    The options to be used by the client. If a MongoDB URI connection string is also provided, these options take precedence over any analogous options present in the URI string.

Options Hash (options):

  • :app_name (String, Symbol)

    Application name that is printed to the mongod logs upon establishing a connection

  • :auth_mech (Symbol)

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

  • :auth_mech_properties (Hash)
  • :auth_source (String)

    The source to authenticate from.

  • :bg_error_backtrace (true | false | nil | Integer)

    Experimental. Set to true to log complete backtraces for errors in background threads. Set to false or nil to not log backtraces. Provide a positive integer to log up to that many backtrace lines.

  • :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 'zstd, 'snappy' and 'zlib'.

  • :direct_connection (true | false)

    Whether to connect directly to the specified seed, bypassing topology discovery. Exactly one seed must be provided.

  • :connect (Symbol)

    Deprecated - use :direct_connection option instead of this option. 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, :load_balanced. If :connect is set to :load_balanced, the driver will behave as if the server is a load balancer even if it isn't connected to a load balancer.

  • :connect_timeout (Float)

    The timeout, in seconds, to attempt a connection.

  • :database (String)

    The database to connect to.

  • :enable_overload_retargeting (true | false)

    Whether the driver deprioritizes a server that returns an overload error, reducing the likelihood of retrying on the same overloaded server. This option works with MongoDB Atlas Server Version 9.0 and above. Default: false.

  • :heartbeat_frequency (Float)

    The interval, in seconds, for the server monitor to refresh its description via hello.

  • :id_generator (Object)

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

  • :load_balanced (true | false)

    Whether to expect to connect to a load balancer.

  • :local_threshold (Integer)

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

  • :logger (Logger)

    A custom logger to use.

  • :log_prefix (String)

    A custom log prefix to use when logging. This option is experimental and subject to change in a future version of the driver.

  • :max_adaptive_retries (Integer)

    The maximum number of retries to attempt when the driver encounters overload errors. This option works with MongoDB Atlas Server Version 9.0 and above. Default: 2.

  • :max_connecting (Integer)

    The maximum number of connections that can be connecting simultaneously. The default is 2. This option should be increased if there are many threads that share the same client and the application is experiencing timeouts while waiting for connections to be established. selecting a server for an operation. The default is 2.

  • :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. Setting this option to zero creates an unlimited connection pool.

  • :max_read_retries (Integer)

    The maximum number of read retries when legacy read retries are in use. Deprecated: this option only affects the legacy retry implementation, which is deprecated and will be removed in a future version.

  • :max_write_retries (Integer)

    The maximum number of write retries when legacy write retries are in use. Deprecated: this option only affects the legacy retry implementation, which is deprecated and will be removed in a future version.

  • :min_pool_size (Integer)

    The minimum size of the connection pool.

  • :monitoring (true, false)

    If false is given, the client is initialized without global SDAM event subscribers and will not publish SDAM events. Command monitoring and legacy events will still be published, and the driver will still perform SDAM and monitor its cluster in order to perform server selection. Built-in driver logging of SDAM events will be disabled because it is implemented through SDAM event subscription. Client#subscribe will succeed for all event types, but subscribers to SDAM events will not be invoked. Values other than false result in default behavior which is to perform normal SDAM event publication.

  • :monitoring_io (true, false)

    For internal driver use only. Set to false to prevent SDAM-related I/O from being done by this client or servers under it. Note: setting this option to false will make the client non-functional. It is intended for use in tests which manually invoke SDAM state transitions.

  • :cleanup (true | false)

    For internal driver use only. Set to false to prevent endSessions command being sent to the server to clean up server sessions when the cluster is disconnected, and to to not start the periodic executor. If :monitoring_io is false, :cleanup automatically defaults to false as well.

  • :password (String)

    The user's password.

  • :platform (String)

    Platform information to include in the metadata printed to the mongod logs upon establishing a connection

  • :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.
  • :read_concern (Hash)

    The read concern option.

  • :read_retry_interval (Float)

    The interval, in seconds, in which reads on a mongos are retried. Deprecated: this option only affects the legacy retry implementation, which is deprecated and will be removed in a future version.

  • :replica_set (Symbol)

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

  • :retry_reads (true | false)

    If true, modern retryable reads are enabled (which is the default). If false, modern retryable reads are disabled and legacy retryable reads are enabled.

  • :retry_writes (true | false)

    Retry writes once when connected to a replica set or sharded cluster. (Default is true.)

  • :scan (true | false)

    Whether to scan all seeds in constructor. The default in driver version 2.x is to do so; driver version 3.x will not scan seeds in constructor. Opt in to the new behavior by setting this option to false. Note: setting this option to nil enables scanning seeds in constructor in driver version 2.x. Driver version 3.x will recognize this option but will ignore it and will never scan seeds in the constructor.

  • :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 published during client construction.

    Note: the client is not fully constructed when sdam_proc is invoked, in particular the cluster is nil at this time. sdam_proc should limit itself to calling #subscribe and #unsubscribe methods on the client only.

  • :server_api (Hash)

    The requested server API version. This hash can have the following items:

    • :version -- string
    • :strict -- boolean
    • :deprecation_errors -- boolean
  • :server_selection_timeout (Integer)

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

  • :socket_timeout (Float)

    The timeout, in seconds, to execute operations on a socket. This option is deprecated, use :timeout_ms instead.

  • :srv_max_hosts (Integer)

    The maximum number of mongoses that the driver will communicate with for sharded topologies. If this option is 0, then there will be no maximum number of mongoses. If the given URI resolves to more hosts than :srv_max_hosts, the client will randomly choose an :srv_max_hosts sized subset of hosts. If srvMaxHosts is provided in the URI options, it takes precedence over this option.

  • :srv_service_name (String)

    The service name to use in the SRV DNS query.

  • :ssl (true, false)

    Whether to use TLS.

  • :ssl_ca_cert (String)

    The file containing concatenated certificate authority certificates used to validate certs passed from the other end of the connection. Intermediate certificates should NOT be specified in files referenced by this option. One of :ssl_ca_cert, :ssl_ca_cert_string or :ssl_ca_cert_object (in order of priority) is required when using :ssl_verify.

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

    An array of OpenSSL::X509::Certificate objects representing the certificate authority certificates used to validate certs passed from the other end of the connection. Intermediate certificates should NOT be specified in files referenced by this option. One of :ssl_ca_cert, :ssl_ca_cert_string or :ssl_ca_cert_object (in order of priority) is required when using :ssl_verify.

  • :ssl_ca_cert_string (String)

    A string containing certificate authority certificate used to validate certs passed from the other end of the connection. This option allows passing only one CA certificate to the driver. Intermediate certificates should NOT be specified in files referenced by this option. One of :ssl_ca_cert, :ssl_ca_cert_string or :ssl_ca_cert_object (in order of priority) is required when using :ssl_verify.

  • :ssl_cert (String)

    The certificate file used to identify the connection against MongoDB. A certificate chain may be passed by specifying the client certificate first followed by any intermediate certificates up to the CA certificate. The file may also contain the certificate's private key, which will be ignored. This option, if present, takes precedence over the values of :ssl_cert_string and :ssl_cert_object

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

    The OpenSSL::X509::Certificate used to identify the connection against MongoDB. Only one certificate may be passed through this option.

  • :ssl_cert_string (String)

    A string containing the PEM-encoded certificate used to identify the connection against MongoDB. A certificate chain may be passed by specifying the client certificate first followed by any intermediate certificates up to the CA certificate. The string may also contain the certificate's private key, which will be ignored, This option, if present, takes precedence over the value of :ssl_cert_object

  • :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_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_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_verify (true, false)

    Whether to perform peer certificate validation and hostname verification. Note that the decision of whether to validate certificates will be overridden if :ssl_verify_certificate is set, and the decision of whether to validate hostnames will be overridden if :ssl_verify_hostname is set.

  • :ssl_verify_certificate (true, false)

    Whether to perform peer certificate validation. This setting overrides :ssl_verify with respect to whether certificate validation is performed.

  • :ssl_verify_hostname (true, false)

    Whether to perform peer hostname validation. This setting overrides :ssl_verify with respect to whether hostname validation is performed.

  • :timeout_ms (Integer)

    The operation timeout in milliseconds. Must be a non-negative integer. An explicit value of 0 means infinite. The default value is unset which means the feature is not enabled.

  • :truncate_logs (true, false)

    Whether to truncate the logs at the default 250 characters.

  • :user (String)

    The user name.

  • :wait_queue_timeout (Float)

    The time to wait, in seconds, in the connection pool for a connection to be checked in. This option is deprecated, use :timeout_ms instead.

  • :wrapping_libraries (Array<Hash>)

    Information about libraries such as ODMs that are wrapping the driver, to be added to metadata sent to the server. Specify the lower level libraries first. Allowed hash keys: :name, :version, :platform.

  • :write (Hash)

    Deprecated. Equivalent to :write_concern option.

  • :write_concern (Hash)

    The write concern options. Can be :w => Integer|String, :wtimeout => Integer (in milliseconds, deprecated), :j => Boolean, :fsync => Boolean.

  • :zlib_compression_level (Integer)

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

  • :resolv_options (Hash)

    For internal driver use only. Options to pass through to Resolv::DNS constructor for SRV lookups.

  • :tracing (Hash)

    OpenTelemetry tracing options.

    • :enabled => Boolean, whether to enable OpenTelemetry tracing. The default value is nil that means that the configuration will be taken from the OTEL_RUBY_INSTRUMENTATION_MONGODB_ENABLED environment variable.
    • :tracer => OpenTelemetry::Trace::Tracer, the tracer to use for tracing. Must be an implementation of OpenTelemetry::Trace::Tracer interface.
    • :query_text_max_length => Integer, the maximum length of the query text to be included in the span attributes. If the query text exceeds this length, it will be truncated. Value 0 means no query text will be included in the span attributes. The default value is nil that means that the configuration will be taken from the OTEL_RUBY_INSTRUMENTATION_MONGODB_QUERY_TEXT_MAX_LENGTH environment variable.
  • :auto_encryption_options (Hash)

    Auto-encryption related options.

    • :key_vault_client => Client | nil, a client connected to the MongoDB instance containing the encryption key vault
    • :key_vault_namespace => String, the namespace of the key vault in the format database.collection
    • :kms_providers => Hash, A hash of key management service (KMS) configuration information. Valid hash keys are :aws, :azure, :gcp, :kmip, :local. There may be more than one kms provider specified.
    • :kms_tls_options => Hash, A hash of TLS options to authenticate to KMS providers, usually used for KMIP servers. Valid hash keys are :aws, :azure, :gcp, :kmip, :local. There may be more than one kms provider specified.
    • :schema_map => Hash | nil, JSONSchema for one or more collections specifying which fields should be encrypted. This option is mutually exclusive with :schema_map_path.
      • Note: Schemas supplied in the schema_map only apply to configuring automatic encryption for client side encryption. Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.
      • Note: Supplying a schema_map provides more security than relying on JSON Schemas obtained from the server. It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending unencrypted data that should be encrypted.
      • Note: If a collection is present on both the :encrypted_fields_map and :schema_map, an error will be raised.
    • :schema_map_path => String | nil A path to a file contains the JSON schema of the collection that stores auto encrypted documents. This option is mutually exclusive with :schema_map.
    • :bypass_auto_encryption => Boolean, when true, disables auto encryption; defaults to false.
    • :extra_options => Hash | nil, options related to spawning mongocryptd (this part of the API is subject to change).
    • :encrypted_fields_map => Hash | nil, maps a collection namespace to a hash describing encrypted fields for queryable encryption.
      • Note: If a collection is present on both the encryptedFieldsMap and schemaMap, an error will be raised.
    • :bypass_query_analysis => Boolean | nil, when true disables automatic analysis of outgoing commands.
    • :crypt_shared_lib_path => [ String | nil ] Path that should be the used to load the crypt shared library. Providing this option overrides default crypt shared library load paths for libmongocrypt.
    • :crypt_shared_lib_required => [ Boolean | nil ] Whether crypt shared library is required. If 'true', an error will be raised if a crypt_shared library cannot be loaded by libmongocrypt.

    Notes on automatic encryption:

    • Automatic encryption is an enterprise only feature that only applies to operations on a collection.
    • Automatic encryption is not supported for operations on a database or view.
    • Automatic encryption requires the authenticated user to have the listCollections privilege.
    • At worst, automatic encryption may triple the number of connections used by the Client at any one time.
    • If automatic encryption fails on an operation, use a MongoClient configured with bypass_auto_encryption: true and use ClientEncryption.encrypt to manually encrypt values.
    • Enabling Client Side Encryption reduces the maximum write batch size and may have a negative performance impact.

Since:

  • 2.0.0



539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
# File 'lib/mongo/client.rb', line 539

def initialize(addresses_or_uri, options = nil)
  options = options ? options.dup : {}

  processed = process_addresses(addresses_or_uri, options)

  uri = processed[:uri]
  addresses = processed[:addresses]
  options = processed[:options]

  # If the URI is an SRV URI, note this so that we can start
  # SRV polling if the topology is a sharded cluster.
  srv_uri = uri if uri.is_a?(URI::SRVProtocol)

  options = self.class.canonicalize_ruby_options(options)

  # The server API version is specified to be a string.
  # However, it is very annoying to always provide the number 1 as a string,
  # therefore cast to the string type here.
  if (server_api = options[:server_api]) && server_api.is_a?(Hash)
    server_api = Options::Redacted.new(server_api)
    if (version = server_api[:version]).is_a?(Integer)
      options[:server_api] = server_api.merge(version: version.to_s)
    end
  end

  # Special handling for sdam_proc as it is only used during client
  # construction
  sdam_proc = options.delete(:sdam_proc)

  # For gssapi service_name, the default option is given in a hash
  # (one level down from the top level).
  merged_options = default_options(options)
  options.each do |k, v|
    default_v = merged_options[k]
    v = default_v.merge(v) if default_v.is_a?(Hash)
    merged_options[k] = v
  end
  options = merged_options

  options.keys.each do |k|
    options.delete(k) if options[k].nil?
  end

  @options = validate_new_options!(options)
  # WriteConcern object support
  #       if @options[:write_concern].is_a?(WriteConcern::Base)
  #         # Cache the instance so that we do not needlessly reconstruct it.
  #         @write_concern = @options[:write_concern]
  #         @options[:write_concern] = @write_concern.options
  #       end
  @options.freeze
  validate_options!(addresses, is_srv: uri.is_a?(URI::SRVProtocol))
  validate_authentication_options!

  database_options = @options.dup
  database_options.delete(:server_api)
  @database = Database.new(self, @options[:database], database_options)

  # Temporarily set monitoring so that event subscriptions can be
  # set up without there being a cluster
  @monitoring = Monitoring.new(@options)

  sdam_proc.call(self) if sdam_proc

  @connect_lock = Mutex.new
  @retry_policy = Retryable::RetryPolicy.new(
    max_retries: @options[:max_adaptive_retries] || Retryable::Backpressure::DEFAULT_MAX_RETRIES
  )
  @connect_lock.synchronize do
    @cluster = Cluster.new(
      addresses,
      @monitoring,
      cluster_options.merge(srv_uri: srv_uri)
    )
  end

  begin
    # Unset monitoring, it will be taken out of cluster from now on
    remove_instance_variable(:@monitoring)

    if @options[:auto_encryption_options]
      @connect_lock.synchronize do
        build_encrypter
      end
    end
  rescue StandardError
    begin
      @cluster.close
    rescue StandardError => e
      log_warn("Error closing cluster in client constructor's exception handler: #{e.class}: #{e}")
      # Drop this exception so that the original exception is raised
    end
    raise
  end

  return unless block_given?

  begin
    yield(self)
  ensure
    close
  end
end

Instance Attribute Details

#clusterMongo::Cluster (readonly)

Returns cluster The cluster of servers for the client.

Returns:

Since:

  • 2.0.0



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

def cluster
  @cluster
end

#databaseMongo::Database (readonly)

Returns database The database the client is operating on.

Returns:

Since:

  • 2.0.0



146
147
148
# File 'lib/mongo/client.rb', line 146

def database
  @database
end

#encrypterMongo::Crypt::AutoEncrypter (readonly)

Returns The object that encapsulates auto-encryption behavior.

Returns:

Since:

  • 2.0.0



153
154
155
# File 'lib/mongo/client.rb', line 153

def encrypter
  @encrypter
end

#optionsHash (readonly)

Returns options The configuration options.

Returns:

  • (Hash)

    options The configuration options.

Since:

  • 2.0.0



149
150
151
# File 'lib/mongo/client.rb', line 149

def options
  @options
end

#retry_policyMongo::Retryable::RetryPolicy (readonly)

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.

Returns The retry policy for backpressure and adaptive retries.

Returns:

Since:

  • 2.0.0



158
159
160
# File 'lib/mongo/client.rb', line 158

def retry_policy
  @retry_policy
end

Class Method Details

.canonicalize_ruby_options(options) ⇒ Object

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.

Lowercases auth mechanism properties, if given, in the specified options, then converts the options to an instance of Options::Redacted.

Since:

  • 2.0.0



1215
1216
1217
1218
1219
1220
1221
1222
# File 'lib/mongo/client.rb', line 1215

def canonicalize_ruby_options(options)
  Options::Redacted.new(Hash[options.map do |k, v|
    if [ :auth_mech_properties, 'auth_mech_properties' ].include?(k) && v
      v = Hash[v.map { |pk, pv| [ pk.downcase, pv ] }]
    end
    [ k, v ]
  end])
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



186
187
188
189
190
# File 'lib/mongo/client.rb', line 186

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



204
205
206
# File 'lib/mongo/client.rb', line 204

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

#closetrue

Close all connections.

Returns:

  • (true)

    Always true.

Since:

  • 2.1.0



916
917
918
919
920
921
922
# File 'lib/mongo/client.rb', line 916

def close
  @connect_lock.synchronize do
    @closed = true
    do_close
  end
  true
end

#close_encryptertrue

Close encrypter and clean up auto-encryption resources.

Returns:

  • (true)

    Always true.

Since:

  • 2.0.0



927
928
929
930
931
# File 'lib/mongo/client.rb', line 927

def close_encrypter
  @encrypter.close if @encrypter

  true
end

#closed?Boolean

Returns:

  • (Boolean)

Since:

  • 2.0.0



907
908
909
# File 'lib/mongo/client.rb', line 907

def closed?
  !!@closed
end

#cluster_optionsObject

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.

Since:

  • 2.0.0



644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
# File 'lib/mongo/client.rb', line 644

def cluster_options
  # We share clusters when a new client with different CRUD_OPTIONS
  # is requested; therefore, cluster should not be getting any of these
  # options upon instantiation
  options.reject do |key, _value|
    CRUD_OPTIONS.include?(key.to_sym)
  end.merge(
    # but need to put the database back in for auth...
    database: options[:database],

    # Put these options in for legacy compatibility, but note that
    # their values on the client and the cluster do not have to match -
    # applications should read these values from client, not from cluster
    max_read_retries: options[:max_read_retries],
    read_retry_interval: options[:read_retry_interval],
    tracer: tracer
  ).tap do |options|
    # If the client has a cluster already, forward srv_uri to the new
    # cluster to maintain SRV monitoring. If the client is brand new,
    # its constructor sets srv_uri manually.
    options.update(srv_uri: cluster.options[:srv_uri]) if cluster
  end
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.

  • options (Hash)

    a customizable set of options

Options Hash (opts):

  • :authorized_databases (true, false)

    A flag that determines which databases are returned based on user privileges when access control is enabled

    See https://mongodb.com/docs/manual/reference/command/listDatabases/ for more information and usage.

  • :session (Session)

    The session to use.

  • :comment (Object)

    A user-provided comment to attach to this command.

Returns:

  • (Array<String>)

    The names of the databases.

Since:

  • 2.0.5



985
986
987
# File 'lib/mongo/client.rb', line 985

def database_names(filter = {}, opts = {})
  list_databases(filter, true, opts).collect { |info| info['name'] }
end

#encrypted_fields_mapHash | nil

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.

Returns encrypted field map hash if provided when creating the client.

Returns:

  • (Hash | nil)

    Encrypted field map hash, or nil if not set.

Since:

  • 2.0.0



1229
1230
1231
# File 'lib/mongo/client.rb', line 1229

def encrypted_fields_map
  @encrypted_fields_map ||= @options.fetch(:auto_encryption_options, {})[:encrypted_fields_map]
end

#get_session(options = {}) ⇒ Session | nil

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.

Returns a session to use for operations if possible.

If :session option is set, validates that session and returns it. Otherwise, if deployment supports sessions, creates a new session and returns it. When a new session is created, the session will be implicit (lifecycle is managed by the driver) if the :implicit option is given, otherwise the session will be explicit (lifecycle managed by the application). If deployment does not support session, returns nil.

Parameters:

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

    a customizable set of options

Options Hash (options):

  • :implicit (true | false)

    When no session is passed in, whether to create an implicit session.

  • :session (Session)

    The session to validate and return.

Returns:

  • (Session | nil)

    Session object or nil if sessions are not supported by the deployment.

Since:

  • 2.0.0



1173
1174
1175
1176
1177
# File 'lib/mongo/client.rb', line 1173

def get_session(options = {})
  get_session!(options)
rescue Error::SessionsNotSupported
  nil
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



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

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



706
707
708
# File 'lib/mongo/client.rb', line 706

def inspect
  "#<Mongo::Client:0x#{object_id} cluster=#{cluster.summary}>"
end

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

Get info for each database.

See https://mongodb.com/docs/manual/reference/command/listDatabases/
for more information and usage.

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.

  • options (Hash)

    a customizable set of options

Options Hash (opts):

  • :authorized_databases (true, false)

    A flag that determines which databases are returned based on user privileges when access control is enabled.

  • :comment (Object)

    A user-provided comment to attach to this command.

  • :session (Session)

    The session to use.

Returns:

  • (Array<Hash>)

    The info for each database.

Since:

  • 2.0.5



1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
# File 'lib/mongo/client.rb', line 1016

def list_databases(filter = {}, name_only = false, opts = {})
  cmd = { listDatabases: 1 }
  cmd[:nameOnly] = !!name_only
  cmd[:filter] = filter unless filter.empty?
  cmd[:authorizedDatabases] = true if opts[:authorized_databases]
  use(Database::ADMIN)
    .database
    .read_command(cmd, opts.merge(op_name: 'listDatabases'))
    .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.

  • options (Hash)

    a customizable set of options

Options Hash (opts):

  • :session (Session)

    The session to use.

Returns:

Since:

  • 2.5.0



1042
1043
1044
1045
1046
# File 'lib/mongo/client.rb', line 1042

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

#max_read_retriesInteger

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.

Get the maximum number of times the client can retry a read operation when using legacy read retries.

Returns:

  • (Integer)

    The maximum number of retries.

Since:

  • 2.0.0



674
675
676
# File 'lib/mongo/client.rb', line 674

def max_read_retries
  options[:max_read_retries] || Cluster::MAX_READ_RETRIES
end

#max_write_retriesInteger

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.

Get the maximum number of times the client can retry a write operation when using legacy write retries.

Returns:

  • (Integer)

    The maximum number of retries.

Since:

  • 2.0.0



694
695
696
# File 'lib/mongo/client.rb', line 694

def max_write_retries
  options[:max_write_retries] || Cluster::MAX_WRITE_RETRIES
end

#monitoringMonitoring

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.

Returns monitoring The monitoring.

Returns:

Since:

  • 2.0.0



168
169
170
171
172
173
174
# File 'lib/mongo/client.rb', line 168

def monitoring
  if cluster
    cluster.monitoring
  else
    @monitoring
  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



890
891
892
# File 'lib/mongo/client.rb', line 890

def 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:

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

Since:

  • 2.0.0



754
755
756
# File 'lib/mongo/client.rb', line 754

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

#read_retry_intervalFloat

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.

Get the interval, in seconds, in which read retries when using legacy read retries.

Returns:

  • (Float)

    The interval.

Since:

  • 2.0.0



684
685
686
# File 'lib/mongo/client.rb', line 684

def read_retry_interval
  options[:read_retry_interval] || Cluster::READ_RETRY_INTERVAL
end

#reconnecttrue

Reconnect the client.

Examples:

Reconnect the client.

client.reconnect

Returns:

  • (true)

    Always true.

Since:

  • 2.1.0



941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
# File 'lib/mongo/client.rb', line 941

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

  @connect_lock.synchronize do
    begin
      do_close
    rescue StandardError
      nil
    end

    @cluster = Cluster.new(addresses, monitoring, cluster_options)

    build_encrypter if @options[:auto_encryption_options]

    @closed = false
  end

  true
end

#reset_cluster!(monitoring: nil) ⇒ Object

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.

Replaces this client's cluster with a fresh instance built from the client's current options. Used by #with so a reconfigured client does not share its cluster with the client it was cloned from.

Parameters:

  • monitoring (Monitoring | nil) (defaults to: nil)

    The monitoring instance to use with the new cluster. If nil, a new instance of Monitoring is created.

Since:

  • 2.0.0



874
875
876
877
878
879
880
# File 'lib/mongo/client.rb', line 874

def reset_cluster!(monitoring: nil)
  @cluster = Cluster.new(
    cluster.addresses.map(&:to_s),
    monitoring || Monitoring.new,
    cluster_options
  )
end

#reset_database!Object

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.

Replaces this client's database with a fresh instance built from the client's current options. Used by #with so a reconfigured client does not share its database with the client it was cloned from.

Since:

  • 2.0.0



862
863
864
# File 'lib/mongo/client.rb', line 862

def reset_database!
  @database = Database.new(self, options[:database], options)
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



732
733
734
735
736
737
738
# File 'lib/mongo/client.rb', line 732

def server_selector
  @server_selector ||= if read_preference
                         ServerSelector.get(read_preference)
                       else
                         ServerSelector.primary
                       end
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.

If the deployment does not support sessions, raises Mongo::Error::InvalidSession. This exception can also be raised when the driver is not connected to a data-bearing server, for example during failover.

Examples:

Start a session.

client.start_session(causal_consistency: true)

Parameters:

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

    The session options. Accepts the options that Session#initialize accepts.

Returns:

Since:

  • 2.5.0



1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
# File 'lib/mongo/client.rb', line 1067

def start_session(options = {})
  session = get_session!(options.merge(implicit: false))
  if block_given?
    begin
      yield session
    ensure
      session.end_session
    end
  else
    session
  end
end

#summaryString

Note:

The exact format and layout of the returned summary string is not part of the driver's public API and may be changed at any time.

Get a summary of the client state.

Returns:

  • (String)

    The summary string.

Since:

  • 2.7.0



718
719
720
# File 'lib/mongo/client.rb', line 718

def summary
  "#<Client cluster=#{cluster.summary}>"
end

#timeout_msInteger | nil

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.

Returns Value of timeout_ms option if set.

Returns:

  • (Integer | nil)

    Value of timeout_ms option if set.

Since:

  • 2.0.0



1235
1236
1237
# File 'lib/mongo/client.rb', line 1235

def timeout_ms
  @options[:timeout_ms]
end

#timeout_secFloat | nil

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.

Returns Value of timeout_ms option converted to seconds.

Returns:

  • (Float | nil)

    Value of timeout_ms option converted to seconds.

Since:

  • 2.0.0



1241
1242
1243
1244
1245
1246
1247
# File 'lib/mongo/client.rb', line 1241

def timeout_sec
  if timeout_ms.nil?
    nil
  else
    timeout_ms / 1_000.0
  end
end

#tracerTracing::Tracer | nil

Get the tracer configured for this client.

Returns:

  • (Tracing::Tracer | nil)

    The tracer configured for this client.

Since:

  • 2.0.0



1252
1253
1254
1255
1256
1257
1258
1259
# File 'lib/mongo/client.rb', line 1252

def tracer
  tracing_opts = @options[:tracing] || {}
  @tracer ||= Tracing.create_tracer(
    enabled: tracing_opts[:enabled],
    query_text_max_length: tracing_opts[:query_text_max_length],
    otel_tracer: tracing_opts[:tracer]
  )
end

#update_options(new_options) ⇒ 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.

Updates this client's options from new_options, validating all options.

The new options may be transformed according to various rules. The final hash of options actually applied to the client is returned.

If options fail validation, this method may warn or raise an exception. If this method raises an exception, the client should be discarded (similarly to if a constructor raised an exception).

Parameters:

  • new_options (Hash)

    The new options to use.

Returns:

  • (Hash)

    Modified new options written into the client.

Since:

  • 2.0.0



819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
# File 'lib/mongo/client.rb', line 819

def update_options(new_options)
  old_options = @options

  new_options = self.class.canonicalize_ruby_options(new_options || {})

  validate_new_options!(new_options).tap do |opts|
    # Our options are frozen
    options = @options.dup
    options.delete(:write) if options[:write] && opts[:write_concern]
    options.delete(:write_concern) if options[:write_concern] && opts[:write]

    options.update(opts)
    @options = options.freeze

    auto_encryption_options_changed =
      @options[:auto_encryption_options] != old_options[:auto_encryption_options]

    # If there are new auto_encryption_options, create a new encrypter.
    # Otherwise, allow the new client to share an encrypter with the
    # original client.
    #
    # If auto_encryption_options are nil, set @encrypter to nil, but do not
    # close the encrypter because it may still be used by the original client.
    if @options[:auto_encryption_options] && auto_encryption_options_changed
      @connect_lock.synchronize do
        build_encrypter
      end
    elsif @options[:auto_encryption_options].nil?
      @connect_lock.synchronize do
        @encrypter = nil
      end
    end

    validate_options!
    validate_authentication_options!
  end
end

#use(name) ⇒ Mongo::Client

Note:

The new client shares the cluster with the original client, and as a result also shares the monitoring instance and monitoring event subscribers.

Creates a new client configured to use the database with the provided name, and using the other options configured in this client.

Examples:

Create a client for the `users' database.

client.use(:users)

Parameters:

  • name (String, Symbol)

    The name of the database to use.

Returns:

Since:

  • 2.0.0



773
774
775
# File 'lib/mongo/client.rb', line 773

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.

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: nil, 'default', 'updateLookup', 'whenAvailable', 'required'.

    The default is to not send a value (i.e. nil), which is equivalent to 'default'. By default, the change notification for partial updates will include a delta describing the changes to the document.

    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.

    When set to 'whenAvailable', configures the change stream to return the post-image of the modified document for replace and update change events if the post-image for this event is available.

    When set to 'required', the same behavior as 'whenAvailable' except that an error is raised if the post-image is not available.

  • :full_document_before_change (String)

    Allowed values: nil, 'whenAvailable', 'required', 'off'.

    The default is to not send a value (i.e. nil), which is equivalent to 'off'.

    When set to 'whenAvailable', configures the change stream to return the pre-image of the modified document for replace, update, and delete change events if it is available.

    When set to 'required', the same behavior as 'whenAvailable' except that an error is raised if the pre-image is not available.

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

  • :comment (Object)

    A user-provided comment to attach to this command.

  • :show_expanded_events (Boolean)

    Enables the server to send the 'expanded' list of change stream events. The list of additional events included with this flag set are: createIndexes, dropIndexes, modify, create, shardCollection, reshardCollection, refineCollectionShardKey.

Returns:

  • (ChangeStream)

    The change stream object.

Since:

  • 2.6.0



1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
# File 'lib/mongo/client.rb', line 1142

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

  view_options = options.dup
  view_options[:cursor_type] = :tailable_await if options[:max_await_time_ms]

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

#with(new_options = nil) ⇒ Mongo::Client

Note:

Depending on options given, the returned client may share the cluster with the original client or be created with a new cluster. If a new cluster is created, the monitoring event subscribers on the new client are set to the default event subscriber set and none of the subscribers on the original client are copied over.

Creates 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: nil)

    The new options to use.

Returns:

Since:

  • 2.0.0



795
796
797
798
799
800
801
802
803
# File 'lib/mongo/client.rb', line 795

def with(new_options = nil)
  clone.tap do |client|
    opts = client.update_options(new_options || Options::Redacted.new)
    client.reset_database!
    # We can't use the same cluster if some options that would affect it
    # have changed.
    client.reset_cluster!(monitoring: opts[:monitoring]) if cluster_modifying?(opts)
  end
end

#with_session(options = {}) ⇒ Object

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.

Creates a session to use for operations if possible and yields it to the provided block.

If :session option is set, validates that session and uses it. Otherwise, if deployment supports sessions, creates a new session and uses it. When a new session is created, the session will be implicit (lifecycle is managed by the driver) if the :implicit option is given, otherwise the session will be explicit (lifecycle managed by the application). If deployment does not support session, yields nil to the block.

When the block finishes, if the session was created and was implicit, or if an implicit session was passed in, the session is ended which returns it to the pool of available sessions.

Parameters:

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

    a customizable set of options

Options Hash (options):

  • :implicit (true | false)

    When no session is passed in, whether to create an implicit session.

  • :session (Session)

    The session to validate and return.

Since:

  • 2.0.0



1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
# File 'lib/mongo/client.rb', line 1199

def with_session(options = {})
  # RUBY-3174 will re-enable this guard; see #assert_not_closed.
  # assert_not_closed

  session = get_session(options)

  yield session
ensure
  session.end_session if session && session.implicit?
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



903
904
905
# File 'lib/mongo/client.rb', line 903

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