Navigation
This version of the documentation is archived and no longer supported.

Creating a Client

Using Mongo::Client

To connect to a MongoDB deployment, create a Mongo::Client object. Provide a list of hosts and options or a connection URI to the Mongo::Client constructor. The client’s selected database defaults to admin.

To create a client to a standalone server, provide one host in the seed list. Optionally, you can force the cluster topology to be standalone without going through the auto-discovery steps.

Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'mydb')
Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'mydb', :connect => :direct)
Mongo::Client.new('mongodb://127.0.0.1:27017/mydb')

To connect to a replica set, pass one or more hosts and the replica set name. The driver’s auto-discovery feature finds all members of the replica set if they are not all provided.

Mongo::Client.new([ '127.0.0.1:27017', '127.0.0.1:27018' ], :database => 'mydb', replica_set: 'myapp')
Mongo::Client.new('mongodb://127.0.0.1:27017,127.0.0.1:27018/mydb?replicaSet=myapp')

To create a client to a sharded cluster, pass one or more mongos hosts. The auto-discovery feature can determine that the servers are mongos instances, but if you would like to bypass the auto-discovery, pass the sharded option to the client.

Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'mydb')
Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'mydb', :connect => :sharded)
Mongo::Client.new('mongodb://127.0.0.1:27017/mydb?connect=sharded')

The URI parser in the driver also accepts the mongodb+srv protocol URIs, for example:

Mongo::Client.new('mongodb+srv://test5.test.build.mongodb.cc')

When an SRV URI is given, the driver does the following:

  1. As part of Client object construction, the SRV URI is resolved to the actual hosts comprising the deployment, as these are defined in the DNS SRV records.
  2. The driver looks up URI options in the DNS TXT records corresponding to the SRV records. These options can be overridden by URI options specified in the URI and by Ruby options, in this order.
  3. If the topology of the constructed Client object is unknown or a sharded cluster, the driver will begin monitoring the specified SRV DNS records for changes and will automatically update the list of servers in the cluster. The updates will stop if the topology becomes a single or a replica set.

Client Options

Mongo::Client’s constructor accepts a number of options configuring the behavior of the driver. The options can be provided in the options hash as Ruby options, in the URI as URI options, or both. If both a Ruby option and the analogous URI option are provided, the Ruby option takes precedence.

Ruby Options

Note

The options passed directly should be symbols.

Note

Unless otherwise specified, Ruby options that deal with times are given in seconds.

Option Description Type Default
:app_name Application name that is printed to the mongod logs upon establishing a connection in server versions >= 3.4. String none
:auth_mech Specifies the authenticaion mechanism to use. Can be one of: :gssapi, :mongodb_cr, :mongodb_x509, :plain, :scram, :scram256. GSSAPI (Kerberos) authentication requires additional dependencies. Symbol If user credentials are not supplied, nil. If user credentials are supplied, the default depends on server version. MongoDB 4.0 and later: :scram256 if user credentials correspond to a user which supports SCRAM-SHA-256 authentication, otherwise :scram. MongoDB 3.0-3.6: :scram. MongoDB 2.6: :mongodb_cr
:auth_mech_properties Provides additional authentication mechanism properties. Hash none
:auth_source Specifies the authentication source. String For MongoDB 2.6 and later: admin if credentials are supplied, otherwise the current database
:auto_encryption_options

A Hash of options for configuring automatic encryption.

  • :key_vault_client - A client connected to the MongoDB instance storing the encryption data keys (Mongo::Client, defaults to the top-level client instance).
  • :key_vault_namespace - The namespace of the key vault collection in the format "database.collection" (String, required).
  • :kms_providers - Key management service configuration information. One or both of the keys :local and :aws must be specified (Hash, required). See the “The kms_providers option`` section of the Client-Side Encryption tutorial for more information about this option.
  • :schema_map - The JSONSchema for one or more collections specifying which fields should be encrypted (Hash, optional, defaults to nil).
  • :bypass_auto_encryption - Whether to skip automatic encryption when performing database operations (Boolean, defaults to false).
  • :extra_options - Options related to spawning mongocryptd (Hash, optional, defaults to nil).

For more information about formatting these options, see the “Auto-Encryption Options” section of the Client-Side Encryption tutorial.

Hash none
:compressors 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’. Array<String> none
:connect Overrides the auto-discovery feature of the driver and forces the cluster topology to a specific type. Choices: :direct, :replica_set or :sharded. Symbol none
:connect_timeout The number of seconds to wait to establish a socket connection before raising an exception. Float 10 seconds
:database The name of the database to connect to. String admin
:heartbeat_frequency The number of seconds for the server monitors to refresh server states asynchronously. Float 10
:id_generator A custom object to generate ids for documents. Must respond to #generate. Object none
:local_threshold Specifies the maximum latency in seconds between the nearest server and the servers that can be available for selection to operate on. Float 0.015
:logger A custom logger. Object Logger
:max_idle_time The maximum seconds a socket can remain idle since it has been checked in to the pool. Integer none
:max_pool_size The maximum size of the connection pool for each server. Integer 5
:max_read_retries The maximum number of read retries, when legacy read retries are used. Set to 0 to disable legacy read retries. Integer 1
:max_write_retries The maximum number of write retries, when legacy write retries are used. Set to 0 to disable legacy write retries. Integer 1
:min_pool_size The minimum number of connections in the connection pool for each server. The driver does not create connections eagerly - a connection is only created when a MongoDB operation is to be executed and there are no available connections, and the total number of established connections to the target server is below :max_pool_size. However, once connections to a particular server are created, up to :min_pool_size connections will be kept in the connection pool by the driver. Integer 0
:monitoring The monitoring object. Object none
:password The password of the user to authenticate with. String none
:platform Platform information to include in the metadata printed to the mongod logs upon establishing a connection in server versions >= 3.4. String none
:read

Specifies the read preference mode and tag sets for selecting servers as a Hash. Allowed Keys in the hash are :mode, :tag_sets and :max_staleness.

{ :read =>
  { :mode => :secondary,
    :tag_sets => [ "berlin" ],
    :max_staleness => 5,
  }
}
Hash { :mode => :primary }
:read_concern Specifies the read concern options. The only valid key is level, for which the valid values are :local, :majority, and :snapshot. Hash none
:read_retry_interval The interval, in seconds, in which reads on a mongos are retried. Integer 5
:replica_set When connecting to a replica set, this is the name of the set to filter servers by. String none
:retry_writes If a single-statement write operation fails from a network error, the driver automatically retries it once when connected to server versions 3.6+. Boolean true
:server_selection_timeout The number of seconds to wait for an appropriate server to be selected for an operation to be executed before raising an exception. Float 30
:socket_timeout The number of seconds to wait for an operation to execute on a socket before raising an exception. Float 5 seconds
:ssl Tell the client to connect to the servers via SSL. Boolean false
:ssl_ca_cert The file path containing concatenated certificate authority certificates used to validate certs passed from the other end of the connection. One of :ssl_ca_cert, :ssl_ca_cert_string or :ssl_ca_cert_object (in order of priority) is required for :ssl_verify. String none
:ssl_ca_cert_object An array of OpenSSL::X509::Certificate representing the certificate authority certificates used to validate certs passed from the other end of the connection. One of :ssl_ca_cert, :ssl_ca_cert_string or :ssl_ca_cert_object (in order of priority) is required for :ssl_verify. Array< OpenSSL::X509::Certificate > none
:ssl_ca_cert_string A string containing concatenated certificate authority certificates used to validate certs passed from the other end of the connection. One of :ssl_ca_cert, :ssl_ca_cert_string or :ssl_ca_cert_object (in order of priority) is required for :ssl_verify. String none
:ssl_cert

Path to the client certificate file used to identify the application to the MongoDB servers. The file may also contain the certificate’s private key; if so, the private key is ignored by this option. The file may also contain intermediate certificates forming the certificate chain from the client certificate to the CA certificate; any intermediate certificates will be parsed by the driver and provided to the OpenSSL context in extra_chain_cert attribute. If intermediate certificates are provided, they must follow the client certificate which must be the first certificate in the file.

This option, if present, takes precedence over :ssl_cert_string and :ssl_cert_object options.

String none
:ssl_cert_object The OpenSSL::X509::Certificate used to identify the application to the MongoDB servers. Only one certificate may be passed through this option. OpenSSL::X509::Certificate none
:ssl_cert_string

A string containing the PEM-encoded certificate used to identify the application to the MongoDB servers. The string may also contain the certificate’s private key; if so, the private key is ignored by this option. The string may also contain intermediate certificates forming the certificate chain from the client certificate to the CA certificate; any intermediate certificates will be parsed by the driver and provided to the OpenSSL context in extra_chain_cert attribute. If intermediate certificates are provided, they must follow the client certificate which must be the first certificatet in the string.

This option, if present, takes precedence over the :ssl_cert_object option.

String none
:ssl_key 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. String none
:ssl_key_object The private key used to identify the connection against MongoDB. OpenSSL::PKey none
:ssl_key_pass_phrase A passphrase for the private key. String none
:ssl_key_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. String none
:ssl_verify 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. Boolean true
:ssl_verify_certificate Whether to perform peer certificate validation. This setting overrides :ssl_verify with respect to whether certificate validation is performed. Boolean true
:ssl_verify_hostname Whether to perform peer hostname validation. This setting overrides :ssl_verify with respect to whether hostname validation is performed. Boolean true
:truncate_logs Whether to truncate the logs at the default 250 characters. Boolean true
:user The name of the user to authenticate with. String none
:wait_queue_timeout The number of seconds to wait for a connection in the connection pool to become available. Float 1
:write Deprecated. Equivalent to :write_concern option. If both :write and :write_concern are specified, their values must be identical. Hash { w: 1 }
:write_concern

Specifies write concern options as a Hash. Keys in the hash can be :w, :wtimeout, :j, :fsync.

{ write_concern: { w: 2 } }
Hash { w: 1 }
:zlib_compression_level The Zlib compression level to use, if using compression. See Ruby’s Zlib module for valid levels. Integer none

URI Options

Since the URI options are required to be in camel case, which is not the Ruby standard, the following table shows URI options and their corresponding Ruby options.

URI options are explained in detail in the Connection URI reference.

Note

Options that are set in milliseconds in the URI are represented as a float in Ruby and the units are seconds.

URI Option Ruby Option
appName=String :app_name => String
authMechanism=String

:auth_mech => Symbol

Auth mechanism values are converted as follows from URI options to Ruby options:

  • GSSAPI => :gssapi
  • MONGODB-CR => :mongodb_cr
  • MONGODB-X509 => :mongodb_x509
  • PLAIN => :plain
  • SCRAM-SHA-1 => :scram
  • SCRAM-SHA-256 => :scram256

If a different value is provided for auth mechanism, it is converted to the Ruby option unmodified and retains its String type. Note that, while currently the driver allows a Client instance to be constructed with an unrecognized auth mechanism, this behavior may change in a future version of the driver.

authMechanismProperties=Strings

{ :auth_mech_properties => { :service_realm => String, :canonicalize_host_name => true|false, :service_name => String } }

Specified as comma-separated key:value pairs, e.g. "SERVICE_REALM:foo,CANONICALIZE_HOST_NAME:TRUE".

authSource=String :auth_source => String
compressors=Strings

:compressors => Array<String>

Specified as a comma-separated list. Note that the Ruby driver only supports zlib compression; however, other drivers may support snappy. For maximum compatibility with drivers, specify "snappy,zlib"; if compatibility with other drivers is not a concern, specify "zlib". Compression is not enabled by default and when using MongoDB 4.0 and earlier, so zlib compression must be manually enabled on the server in order for the Ruby driver to compress wire protocol data.

connect=String :connect => Symbol
connectTimeoutMS=Integer :connect_timeout => Float
fsync=Boolean { :write_concern => { :fsync => true|false }}
heartbeatFrequencyMS=Integer :heartbeat_frequency => Float
journal=Boolean { :write_concern => { :j => true|false }}
localThresholdMS=Integer :local_threshold => Float
maxIdleTimeMS=Integer :max_idle_time => Float
maxStalenessSeconds=Integer

{ :read => { :max_staleness => Integer }}

If the maxStalenessSeconds URI option value is -1, the driver treats this as if the option was not given at all. Otherwise, if the option value is numeric, the Ruby option is set to the specified value converted to an Integer. Note that numeric values greater than 0 but less than 90, or less than -1, are accepted by the Client constructor but will cause server selection to fail (unless the option is changed via, for example, the with method prior to any operations being performed on the driver). If the option value is non-numeric, it is ignored and the driver treats this case as if the option was not given at all.

maxPoolSize=Integer :max_pool_size => Integer
minPoolSize=Integer :min_pool_size => Integer
readConcernLevel=String :read_concern => Hash
readPreference=String { :read => { :mode => Symbol }}
readPreferenceTags=Strings

{ :read => { :tag_sets => Array<Hash> }}

Each instance of the readPreferenceTags field is a comma-separated key:value pair which will appear in the :tag_sets array in the order they are specified. For instance, "readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:ny" will be converted to [ { 'dc' => 'ny', 'rack' => '1' }, { 'dc' => 'ny' }].

replicaSet=String :replica_set => String
retryWrites=Boolean :retry_writes => boolean
serverSelectionTimeoutMS=Integer :server_selection_timeout => Float
socketTimeoutMS=Integer :socket_timeout => Float
ssl=Boolean :ssl => true|false
tls=Boolean :ssl => boolean
tlsAllowInvalidCertificates=Boolean

:ssl_verify_certificate => boolean

Because tlsAllowInvalidCertificates uses true to signify that verification should be disabled and ssl_verify_certificate uses false to signify that verification should be disabled, the boolean is inverted before being used to set ssl_verify_certificate.

tlsAllowInvalidHostnames=Boolean

:ssl_verify_hostname => boolean

Because tlsAllowInvalidHostnames uses true to signify that verification should be disabled and ssl_verify_hostname uses false to signify that verification should be disabled, the boolean is inverted before being used to set ssl_verify_hostname.

tlsCAFile=String :ssl_ca_cert => String
tlsCertificateKeyFile=String :ssl_cert => String
tlsCertificateKeyFile=String :ssl_key => String
tlsCertificateKeyFilePassword=String :ssl_key_pass_phrase => String
tlsInsecure=Boolean

:ssl_verify => boolean

Because tlsInsecure uses true to signify that verification should be disabled and ssl_verify uses false to signify that verification should be disabled, the boolean is inverted before being used to set ssl_verify.

w=Integer|String { :write_concern => { :w => Integer|String }}
waitQueueTimeoutMS=Integer :wait_queue_timeout => Float
wtimeoutMS=Integer { :write_concern => { :wtimeout => Integer }}
zlibCompressionLevel=Integer :zlib_compression_level => Integer

Timeout Options

server_selection_timeout

When executing an operation, the number of seconds to wait for the driver to find an appropriate server to send an operation to. Defaults to 30.

In replica set deployments, this timeout should be set to exceed the typical replica set election times in order for the driver to transparently handle primary changes. This timeout also allows the application and the database to be started simultaneously; the application will wait up to this much time for the database to become available.

If the application server is behind a reverse proxy, server selection timeout should be lower than the request timeout configured on the reverse proxy (for example, this applies to deployments on Heroku which has a fixed 30 second timeout in the routing layer). In development this value can be lowered to provide quicker failure when the server is not running.

socket_timeout

The number of seconds to wait for a socket read or write to complete on regular (non-monitoring) connections. Default is no timeout.

This timeout should take into account both network latency and operation duration. For example, setting this timeout to 5 seconds will abort queries taking more than 5 seconds to execute on the server with Mongo::Error::SocketTimeoutError.

Note that even though by default there is no socket timeout set, the operating system may still time out read operations depending on its configuration. The keepalive settings are intended to detect broken network connections (as opposed to aborting operations simply because they take a long time to execute).

Note that if an operation is timed out by the driver due to exceeding the socket_timeout value, it is not aborted on the server. For this reason it is recommended to use max_time_ms option for potentially long running operations, as this will abort their execution on the server.

This option does not apply to monitoring connections.

connect_timeout

The number of seconds to wait for a socket connection to be established to a server. Defaults to 10. This timeout is also used as both connect timeout and socket timeout for monitoring connections.

wait_queue_timeout

The number of seconds to wait for a connection in the connection pool to become available. Defaults to 10.

As of driver version 2.11, this timeout should be set to a value at least as large as connect_timeout because connection pool now fully establishes connections prior to returning them, which may require several network round trips.

max_time_ms

Specified as an option on a particular operation, the number of milliseconds to allow the operation to execute for on the server. Not set by default.

Consider using this option instead of a socket_timeout for potentially long running operations to be interrupted on the server when they take too long.

wtimeout

The number of milliseconds to wait for a write to be acknowledged by the number of servers specified in the write concern. Not set by default, which instructs the server to apply its default. This option can be set globally on the client or passed to individual operations under :write_concern.

TLS Connections

To connect to the MongoDB cluster using TLS, pass the ssl Ruby option or the tls URI option to the Mongo::Client constructor. TLS must be explicitly requested on the client side when the deployment requires TLS connections - there is currently no automatic detection of whether the deployment requires TLS.

The driver will attempt to verify the server’s TLS certificate by default, and will abort the connection if this verification fails. In order for this verification to succeed, you may need to specify the certificate authority that the server certificate is signed with via tlsCAFile URI option or ssl_ca_cert Ruby option. If these options are not given, the driver will use the default system root certificate store as the trust anchor; if these options are given, the default system root certificate store will not be used. To omit TLS certificate verification by the client, which is not recommended, specify tlsInsecure=true URI option or ssl_verify: false Ruby option.

By default, MongoDB server will verify the connecting clients’ TLS certificates, which requires the client to specify a client certificate when connecting. This can be accomplished through tlsCertificateKeyFile URI option which takes as the argument the path to a single file containing both the certificate and the corresponding private key, or through :ssl_cert and :ssl_key Ruby options. The Ruby options allow passing separace certificate and key files to the driver, but also can be pointed at the single PEM file containing both the certificate and the corresponding private key. Further information on configuring MongoDB server for TLS is available in the MongoDB manual.

Using Intermediate Certificates

It is possible to use certificate chains for both the client and the server certificates. When using chains, the certificate authority parameter should be configured to contain the trusted root certificates only; the intermediate certificates, if any, should be provided in the server or client certificates by concatenating them after the leaf server and client certificates, respectively.

:ssl_cert and :ssl_cert_string Ruby options, as well as tlsCertificateKeyFile URI option, support certificate chains. :ssl_cert_object Ruby option, which takes an instance of OpenSSL::X509::Certificate, does not support certificate chains.

The Ruby driver performs strict X.509 certificate verification, which requires that both of the following fields are set in the intermediate certificate(s):

  • X509v3 Basic Constraints: CA: TRUE – Can sign certificates
  • X509v3 Key Usage: Key Cert Sign – Can sign certificates

More information about these flags can be found here.

It is a common pitfall to concatenate intermediate certificates to the root CA certificates passed in tlsCAFile / ssl_ca_cert options. By doing so, the intermediate certificates are elevated to trusted status and are themselves not verified against the actual CA root. More information on this issue is available here.

Specifying Multiple CA Certificates

:ssl_ca_cert Ruby option and tlsCAFile URI option can be used with a file containing multiple certificates. All certificates thus referenced will become trust anchors.

:ssl_ca_cert_object option takes an array of certificates, and thus can also be used to add multiple certificates as certificate authorities.

:ssl_ca_cert_string option supports passing only one CA certificate to the driver.

Intermediate certificates should not be specified in files given to any of these options, because they would then not be verified against actual trusted CA certificates.

IPv4/IPv6 Connections

When a client is constructed with localhost as the host name, it will attempt an IPv4 connection only (i.e. if localhost resolves to 127.0.0.1 and ::1, the driver will only try to connect to 127.0.0.1).

When a client is constructed with hostnames other than localhost, it will attempt both IPv4 and IPv6 connections depending on the addresses that the hostnames resolve to. The driver respects the order in which getaddrinfo returns the addresses, and will attempt to connect to them sequentially. The first successful connection will be used.

The driver does not currently implement the Happy Eyeballs algorithm.

TCP Keepalive Configuration

The driver sets TCP keepalive by default. The following default values are also set if the system value can be determined and if the driver default value is less than the system value.

  • tcp_keepalive_time: 300 seconds
  • tcp_keepalive_intvl: 10 seconds
  • tcp_keepalive_cnt: 9 probes

Please see the MongoDB Diagnostics FAQ keepalive section for instructions on setting these values at the system level.

Details on Connection Pooling

Mongo::Client instances have a connection pool per server that the client is connected to. The pool creates connections on demand to support concurrent MongoDB operations issued by the application. There is no thread-affinity for connections.

The client instance opens one additional connection per known server for monitoring the server’s state.

The size of each connection pool is capped at max_pool_size, which defaults to 5. When a thread in the application begins an operation on MongoDB, it tries to retrieve a connection from the pool to send that operation on. If there are some connections available in the pool, it checks out a connection from the pool and uses it for the operation. If there are no connections available and the size of the pool is less than the max_pool_size, a new connection will be created. If all connections are in use and the pool has reached its maximum size, the thread waits for a connection to be returned to the pool by another thread.

The number of seconds the thread will wait for a connection to become available is configurable. This setting, called wait_queue_timeout, is defined in seconds. If this timeout is reached, a Timeout::Error is raised. The default is 1 second.

As of driver version 2.11, the driver eagerly creates connections up to min_pool_size setting. Prior to driver version 2.11, the driver always created connections on demand. In all versions of the driver, once a connection is established, it will be kept in the pool by the driver as long as the pool size does not exceed min_pool_size.

Note that, if min_pool_size is set to a value greater than zero, the driver will establish that many connections to secondaries in replica set deployments even if the application does not perform secondary reads. The purpose of these connections is to provide faster failover when the primary changes.

Here is an example of estimating the number of connections a multi-threaded application will open: A client connected to a 3-node replica set opens 3 monitoring sockets. It also opens as many sockets as needed to support a multi-threaded application’s concurrent operations on each server, up to max_pool_size. If the application only uses the primary (the default), then only the primary connection pool grows and the total connections is at most 8 (5 connections for the primary pool + 3 monitoring connections). If the application uses a read preference to query the secondaries, their pools also grow and the total connections can reach 18 (5 + 5 + 5 + 3).

The default configuration for a Mongo::Client works for most applications:

client = Mongo::Client.new(["localhost:27017"])

Create this client once for each process, and reuse it for all operations. It is a common mistake to create a new client for each request, which is very inefficient and not what the client was designed for.

To support extremely high numbers of concurrent MongoDB operations within one process, increase max_pool_size:

client = Mongo::Client.new(["localhost:27017"], max_pool_size: 200)

Any number of threads are allowed to wait for connections to become available, and they can wait the default (1 second) or the wait_queue_timeout setting:

client = Mongo::Client.new(["localhost:27017"], wait_queue_timeout: 0.5)

When #close is called on a client by any thread, all connections are closed:

client.close

Usage with Forking Servers

Note: Applications using Mongoid should follow Mongoid’s forking guidance. The sample code below is provided for applications using the Ruby driver directly.

When using the Mongo Ruby driver with a forking web server such as Unicorn, worker processes should generally each have their own Mongo::Client instances. This is because:

  1. The background threads remain in the parent process and are not transfered to the child process.
  2. File descriptors like network sockets are shared between parent and child processes.

It is recommended to not create any Mongo::Client instances prior to the fork. If the parent process needs to perform operations on the MongoDB database, reset the client in an after_fork handler which is defined in unicorn.rb:

after_fork do |server, worker|
  $client.close
  $client.reconnect
end

The above code assumes your Mongo::Client instance is stored in the $client global variable. It also keeps the MongoDB connection in the parent process around, and this connection will continue to consume resources such as a connection slot. If the parent process performs one time operation(s) on MongoDB and does not need its MongoDB connection once workers are forked, the following code will close the connection in the parent:

before_fork do |server, worker|
  $client.close
end

after_fork do |server, worker|
  $client.reconnect
end

Note: This pattern should be used with Ruby driver version 2.6.2 or higher. Previous driver versions did not recreate monitoring threads when reconnecting.

Note: If the parent process performs operations on the Mongo client and does not close it, the parent process will continue consuming a connection slot in the cluster and will continue monitoring the cluster for as long as the parent remains alive.

Details on Retryable Reads

The driver implements two mechanisms for retrying reads: modern and legacy. As of driver version 2.9.0, the modern mechanism is used by default, and the legacy mechanism is deprecated.

Modern Retryable Reads

When the modern mechanism is used, read operations are retried once in the event of a network error, a “not master” error, or a “node is recovering” error. The following operations are covered:

When an operation returns a cursor, only the initial read command can be retried. getMore operations on cursors are not retried by driver version 2.9.0 or newer. Additionally, when a read operation is retried, a new server for the operation is selected; this may result in the retry being sent to a different server from the one which received the first read.

The behavior of modern retryable reads is covered in detail by the retryable reads specification.

Note that the modern retryable reads can only be used with MongoDB 3.6 and higher servers. When used with MongoDB 3.4 and lower servers, Ruby driver version 2.9.0 and higher will not retry reads by default - the application must explicitly request legacy retryable reads by setting the retry_reads: false client option or using retryReads=false URI option.

Legacy Retryable Reads

The legacy read retry behavior of the Ruby driver is available by setting the retry_reads: false client option or passing the retryReads=false URI option to the client.

When using legacy read retry behavior, the number of retries can be set by specifying the max_read_retries client option. When using driver version 2.9.0 or higher, the set of operations which would be retried with legacy retryable reads is identical to the one described above for modern retryable reads. In older driver versions the behavior of legacy retryable writes was different in that some of the operations were not retried.

As of driver version 2.9.0, legacy read retries perform server selection prior to retrying the operation, as modern retriable writes do. In older driver versions read retries would be sent to the same server which the initial read was sent to.

Disabling Retryable Reads

To disable all read retries, set the following client options: retry_reads: false, max_read_retries: 0.

Details on Retryable Writes

The driver implements two mechanisms for retrying writes: modern and legacy. As of driver version 2.9.0, the modern mechanism is used by default on servers that support it, and the legacy mechanism is deprecated and disabled by default on all server versions.

The following write methods used in day-to-day operations on collections are subject to write retries:

  • collection#insert_one
  • collection#update_one
  • collection#delete_one
  • collection#replace_one
  • collection#find_one_and_update
  • collection#find_one_and_replace
  • collection#find_one_and_delete
  • collection#bulk_write (for all single statement ops, i.e. not for update_many or delete_many)

Modern Retryable Writes

The modern mechanism will retry failing writes once when the driver is connected to a MongoDB 3.6 or higher replica set or a sharded cluster, because they require an oplog on the serer. Modern mechanism will not retry writes when the driver is connected to a standalone MongoDB server or server versions 3.4 or older.

The following errors will cause writes to be retried:

  • Network errors including timeouts
  • “not master” errors
  • “node is recovering” errors

Prior to retrying the write the driver will perform server selection, since the server that the original write was sent to is likely no longer usable.

Legacy Retryable Writes

If modern retryable writes mechanism is disabled by setting the client option retry_writes: false or by using the retryWrites=false URI option, the driver will utilize the legacy retryable writes mechanism. The legacy mechanism retries writes on the same operations as the modern mechanism. By default the legacy mechanism retries once, like the modern mechanism does; to change the number of retries, set :max_write_retries client option.

The difference between legacy and modern retry mechanisms is that the legacy mechanism retries writes for a different set of errors compared to the modern mechanism, and specifically does not retry writes when a network timeout is encountered.

Disabling Retryable Writes

To disable all write retries, set the following client options: retry_writes: false, max_write_retries: 0.

Logging

You can either use the default global driver logger or set your own. To set your own:

Mongo::Logger.logger = other_logger

See the Ruby Logger documentation for more information on the default logger API and available levels.

Changing the Logger Level

To change the logger level:

Mongo::Logger.logger.level = Logger::WARN

For more control, a logger can be passed to a client for per-client control over logging.

my_logger = Logger.new($stdout)
Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test', :logger => my_logger )

Truncation

The default logging truncates logs at 250 characters by default. To turn this off pass an option to the client instance.

Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test', :truncate_logs => false )

Development Configuration

Driver’s default configuration is suitable for production deployment. In development, some settings can be adjusted to provide a better developer experience.

  • :server_selection_timeout: set this to a low value (e.g., 1) if your MongoDB server is running locally and you start it manually. A low server selection timeout will cause the driver to fail quickly when there is no server running.

Production Configuration

Please consider the following when deploying an application using the Ruby driver in production:

  • As of driver version 2.11, the :min_pool_size client option is completely respected - the driver will create that many connections to each server identified as a standalone, primary or secondary. In previous driver versions the driver created connections on demand. Applications using :min_pool_size will see an increase in the number of idle connections to all servers as of driver version 2.11, and especially to secondaries in replica set deployments and to nodes in sharded clusters.
  • If the application is reverse proxied to by another web server or a load balancer, server_selection_timeout should generally be set to a lower value than the reverse proxy’s read timeout. For exampe, Heroku request timeout is 30 seconds and is not configurable; if deploying a Ruby application using MongoDB to Heroku, consider lowering server selection timeout to 20 or 15 seconds.