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

[
  :database,
  :read, :read_concern,
  :write, :write_concern,
  :retry_reads, :max_read_retries, :read_retry_interval,
  :retry_writes, :max_write_retries,

  # 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 revsit
  # using the same cluster object with different server selection timeouts.
].freeze
VALID_OPTIONS =

Valid client options.

Since:

  • 2.1.2

[
  :app_name,
  :auth_mech,
  :auth_mech_properties,
  :auth_source,
  :cleanup,
  :compressors,
  :connect,
  :connect_timeout,
  :database,
  :heartbeat_frequency,
  :id_generator,
  :local_threshold,
  :logger,
  :max_idle_time,
  :max_pool_size,
  :max_read_retries,
  :max_write_retries,
  :min_pool_size,
  :monitoring,
  :monitoring_io,
  :password,
  :platform,
  :read,
  :read_concern,
  :read_retry_interval,
  :replica_set,
  :retry_reads,
  :retry_writes,
  :scan,
  :sdam_proc,
  :server_selection_timeout,
  :socket_timeout,
  :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,
  :truncate_logs,
  :user,
  :wait_queue_timeout,
  :write,
  :write_concern,
  :zlib_compression_level,
].freeze
VALID_COMPRESSORS =

The compression algorithms supported by the driver.

Since:

  • 2.5.0

[ Mongo::Protocol::Compressed::ZLIB ].freeze

Constants included from Loggable

Loggable::PREFIX

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Loggable

#log_debug, #log_error, #log_fatal, #log_info, #log_warn, #logger

Constructor Details

#initialize(addresses_or_uri, options = nil) {|_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'])

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 in server versions >= 3.4.

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

  • :compressors (Array<String>)

    A list of potential compressors to use, in order of preference. The driver chooses the first compressor that is also supported by the server. Currently the driver only supports 'zlib'.

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

  • :connect_timeout (Float)

    The timeout, in seconds, to attempt a connection.

  • :database (String)

    The database to connect to.

  • :heartbeat_frequency (Float)

    The number of seconds for the server monitor to refresh it's description via ismaster.

  • :id_generator (Object)

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

  • :local_threshold (Integer)

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

  • :logger (Logger)

    A custom logger if desired.

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

  • :max_read_retries (Integer)

    The maximum number of read retries when legacy read retries are in use.

  • :max_write_retries (Integer)

    The maximum number of write retries when legacy write retries are in use.

  • :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 in server versions >= 3.4.

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

  • :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 versions 3.6 and up. (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 dispatched 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_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.

  • :ssl (true, false)

    Whether to use SSL.

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

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

  • :write (Hash)

    Deprecated. Equivalent to :write_concern option.

  • :write_concern (Hash)

    The write concern options. Can be :w => Integer|String, :fsync => Boolean, :j => Boolean.

  • :zlib_compression_level (Integer)

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

Yields:

  • (_self)

Yield Parameters:

  • _self (Mongo::Client)

    the object that the method was called on

Since:

  • 2.0.0



366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'lib/mongo/client.rb', line 366

def initialize(addresses_or_uri, options = nil)
  if options
    options = options.dup
  else
    options = {}
  end

  if addresses_or_uri.is_a?(::String)
    uri = URI.get(addresses_or_uri, options)
    addresses = uri.servers
    uri_options = uri.client_options.dup
    # Special handing for :write and :write_concern: allow client Ruby
    # options to override URI options, even when the Ruby option uses the
    # deprecated :write key and the URI option uses the current
    # :write_concern key
    if options[:write]
      uri_options.delete(:write_concern)
    end
    options = uri_options.merge(options)
  else
    addresses = addresses_or_uri
  end

  unless options[:retry_reads] == false
    options[:retry_reads] = true
  end
  unless options[:retry_writes] == false
    options[:retry_writes] = true
  end

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

  @options = validate_new_options!(Database::DEFAULT_OPTIONS.merge(options))
=begin 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
=end
  @options.freeze
  validate_options!

  @database = Database.new(self, @options[:database], @options)

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

  if sdam_proc
    sdam_proc.call(self)
  end

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

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

  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



112
113
114
# File 'lib/mongo/client.rb', line 112

def cluster
  @cluster
end

#databaseMongo::Database (readonly)

Returns database The database the client is operating on.

Returns:

Since:

  • 2.0.0



115
116
117
# File 'lib/mongo/client.rb', line 115

def database
  @database
end

#optionsHash (readonly)

Returns options The configuration options.

Returns:

  • (Hash)

    options The configuration options.

Since:

  • 2.0.0



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

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



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

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



164
165
166
# File 'lib/mongo/client.rb', line 164

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

#close(wait = false) ⇒ true

Close all connections.

Examples:

Disconnect the client.

client.close

Parameters:

  • wait (Boolean) (defaults to: false)

    Whether to wait for background threads to finish running.

Returns:

  • (true)

    Always true.

Since:

  • 2.1.0



659
660
661
662
# File 'lib/mongo/client.rb', line 659

def close(wait=false)
  @cluster.disconnect!(wait)
  true
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



431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/mongo/client.rb', line 431

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(
    server_selection_semaphore: @server_selection_semaphore,
    # 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],
  )
end

#database_names(filter = {}, opts = {}) ⇒ Array<String>

Get the names of all databases.

Examples:

Get the database names.

client.database_names

Parameters:

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

    The filter criteria for getting a list of databases.

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

    The command options.

Returns:

  • (Array<String>)

    The names of the databases.

Since:

  • 2.0.5



692
693
694
# File 'lib/mongo/client.rb', line 692

def database_names(filter = {}, opts = {})
  list_databases(filter, true, opts).collect{ |info| info['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



176
177
178
# File 'lib/mongo/client.rb', line 176

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



488
489
490
# File 'lib/mongo/client.rb', line 488

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.

Examples:

Get the info for each database.

client.list_databases

Parameters:

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

    The filter criteria for getting a list of databases.

  • name_only (true, false) (defaults to: false)

    Whether to only return each database name without full metadata.

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

    The command options.

Returns:

  • (Array<Hash>)

    The info for each database.

Since:

  • 2.0.5



708
709
710
711
712
713
# File 'lib/mongo/client.rb', line 708

def list_databases(filter = {}, name_only = false, opts = {})
  cmd = { listDatabases: 1 }
  cmd[:nameOnly] = !!name_only
  cmd[:filter] = filter unless filter.empty?
  use(Database::ADMIN).database.read_command(cmd, opts).first[Database::DATABASES]
end

#list_mongo_databases(filter = {}, opts = {}) ⇒ Array<Mongo::Database>

Returns a list of Mongo::Database objects.

Examples:

Get a list of Mongo::Database objects.

client.list_mongo_databases

Parameters:

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

    The filter criteria for getting a list of databases.

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

    The command options.

Returns:

Since:

  • 2.5.0



726
727
728
729
730
# File 'lib/mongo/client.rb', line 726

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



456
457
458
# File 'lib/mongo/client.rb', line 456

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



476
477
478
# File 'lib/mongo/client.rb', line 476

def max_write_retries
  options[:max_write_retries] || Cluster::MAX_WRITE_RETRIES
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



630
631
632
# File 'lib/mongo/client.rb', line 630

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:

    • :read – 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



539
540
541
# File 'lib/mongo/client.rb', line 539

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



466
467
468
# File 'lib/mongo/client.rb', line 466

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



672
673
674
675
676
677
678
679
# File 'lib/mongo/client.rb', line 672

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

  @cluster.disconnect! rescue nil

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

#server_selectorMongo::ServerSelector

Get the server selector. It either uses the read preference defined in the client options or defaults to a Primary server selector.

Examples:

Get the server selector.

client.server_selector

Returns:

  • (Mongo::ServerSelector)

    The server selector using the user-defined read preference or a Primary server selector default.

Since:

  • 2.5.0



517
518
519
520
521
522
523
# File 'lib/mongo/client.rb', line 517

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



751
752
753
754
# File 'lib/mongo/client.rb', line 751

def start_session(options = {})
  cluster.send(:get_session, self, options.merge(implicit: false)) ||
    (raise Error::InvalidSession.new(Session::SESSIONS_NOT_SUPPORTED))
end

#summaryString

Note:

This method is experimental and subject to change.

Get a summary of the client state.

Examples:

Inspect the client.

client.summary

Returns:

  • (String)

    Summary string.

Since:

  • 2.7.0



503
504
505
# File 'lib/mongo/client.rb', line 503

def summary
  "#<Client cluster=#{cluster.summary}>"
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



606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
# File 'lib/mongo/client.rb', line 606

def update_options(new_options)
  validate_new_options!(new_options).tap do |opts|
    # Our options are frozen
    options = @options.dup
    if options[:write] && opts[:write_concern]
      options.delete(:write)
    end
    if options[:write_concern] && opts[:write]
      options.delete(:write_concern)
    end
    options.update(opts)
    @options = options.freeze
    validate_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



558
559
560
# File 'lib/mongo/client.rb', line 558

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.

As of version 3.6 of the MongoDB server, a “$changeStream“ pipeline stage is supported in the aggregation framework. As of version 4.0, this stage 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: 'default', 'updateLookup'. Defaults to 'default'. 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.

  • :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. Only recognized by server versions 4.0+.

Returns:

  • (ChangeStream)

    The change stream object.

Since:

  • 2.6.0



789
790
791
792
793
794
795
796
797
# File 'lib/mongo/client.rb', line 789

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

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

#with(new_options = Options::Redacted.new) ⇒ 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: Options::Redacted.new)

    The new options to use.

Returns:

Since:

  • 2.0.0



580
581
582
583
584
585
586
587
588
589
590
# File 'lib/mongo/client.rb', line 580

def with(new_options = Options::Redacted.new)
  clone.tap do |client|
    opts = client.update_options(new_options)
    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



644
645
646
# File 'lib/mongo/client.rb', line 644

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