Class: Mongo::Client
- Inherits:
-
Object
- Object
- Mongo::Client
- 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.
Constant Summary collapse
- CRUD_OPTIONS =
The options that do not affect the behavior of a cluster and its subcomponents.
[ :auto_encryption_options, :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.
[ :app_name, :auth_mech, :auth_mech_properties, :auth_source, :auto_encryption_options, :cleanup, :compressors, :connect, :connect_timeout, :database, :heartbeat_frequency, :id_generator, :local_threshold, :logger, :log_prefix, :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, :resolv_options, :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.
[ Mongo::Protocol::Compressed::ZLIB ].freeze
Constants included from Loggable
Instance Attribute Summary collapse
-
#cluster ⇒ Mongo::Cluster
readonly
Cluster The cluster of servers for the client.
-
#database ⇒ Mongo::Database
readonly
Database The database the client is operating on.
-
#encrypter ⇒ Mongo::Crypt::AutoEncrypter
readonly
The object that encapsulates auto-encryption behavior.
-
#options ⇒ Hash
readonly
Options The configuration options.
Instance Method Summary collapse
-
#==(other) ⇒ true, false
(also: #eql?)
Determine if this client is equivalent to another object.
-
#[](collection_name, options = {}) ⇒ Mongo::Collection
Get a collection object for the provided collection name.
-
#close ⇒ true
Close all connections.
-
#close_encrypter ⇒ true
Close encrypter and clean up auto-encryption resources.
- #cluster_options ⇒ Object private
-
#database_names(filter = {}, opts = {}) ⇒ Array<String>
Get the names of all databases.
-
#hash ⇒ Integer
Get the hash value of the client.
-
#initialize(addresses_or_uri, options = nil) ⇒ Client
constructor
Instantiate a new driver client.
-
#inspect ⇒ String
Get an inspection of the client as a string.
-
#list_databases(filter = {}, name_only = false, opts = {}) ⇒ Array<Hash>
Get info for each database.
-
#list_mongo_databases(filter = {}, opts = {}) ⇒ Array<Mongo::Database>
Returns a list of Mongo::Database objects.
-
#max_read_retries ⇒ Integer
private
Get the maximum number of times the client can retry a read operation when using legacy read retries.
-
#max_write_retries ⇒ Integer
private
Get the maximum number of times the client can retry a write operation when using legacy write retries.
-
#read_concern ⇒ Hash
Get the read concern for this client.
-
#read_preference ⇒ BSON::Document
Get the read preference from the options passed to the client.
-
#read_retry_interval ⇒ Float
private
Get the interval, in seconds, in which read retries when using legacy read retries.
-
#reconnect ⇒ true
Reconnect the client.
-
#server_selector ⇒ Mongo::ServerSelector
Get the server selector.
-
#start_session(options = {}) ⇒ Session
Start a session.
-
#summary ⇒ String
Get a summary of the client state.
-
#update_options(new_options) ⇒ Hash
private
Updates this client’s options from new_options, validating all options.
-
#use(name) ⇒ Mongo::Client
Creates a new client configured to use the database with the provided name, and using the other options configured in this client.
-
#watch(pipeline = [], options = {}) ⇒ ChangeStream
As of version 3.6 of the MongoDB server, a “$changeStream“ pipeline stage is supported in the aggregation framework.
-
#with(new_options = Options::Redacted.new) ⇒ Mongo::Client
Creates a new client with the passed options merged over the existing options of this client.
-
#write_concern ⇒ Mongo::WriteConcern
Get the write concern for this client.
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.
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 |
# File 'lib/mongo/client.rb', line 418 def initialize(addresses_or_uri, = nil) = ? .dup : {} srv_uri = nil if addresses_or_uri.is_a?(::String) uri = URI.get(addresses_or_uri, ) if uri.is_a?(URI::SRVProtocol) # 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 end addresses = uri.servers = uri..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 [:write] .delete(:write_concern) end = .merge() @srv_records = uri.srv_records else addresses = addresses_or_uri @srv_records = nil end # Special handling for sdam_proc as it is only used during client # construction sdam_proc = .delete(:sdam_proc) = ().merge() = () =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 .freeze @database = Database.new(self, [:database], ) # Temporarily set monitoring so that event subscriptions can be # set up without there being a cluster @monitoring = Monitoring.new() if sdam_proc sdam_proc.call(self) end @connect_lock = Mutex.new @connect_lock.synchronize do @cluster = Cluster.new(addresses, @monitoring, .merge(srv_uri: srv_uri)) end begin # Unset monitoring, it will be taken out of cluster from now on remove_instance_variable('@monitoring') if [:auto_encryption_options] @connect_lock.synchronize do build_encrypter end end yield(self) if block_given? rescue begin @cluster.disconnect! rescue => e log_warn("Eror disconnecting cluster in client constructor's exception handler: #{e.class}: #{e}") # Drop this exception so that the original exception is raised end raise end end |
Instance Attribute Details
#cluster ⇒ Mongo::Cluster (readonly)
Returns cluster The cluster of servers for the client.
116 117 118 |
# File 'lib/mongo/client.rb', line 116 def cluster @cluster end |
#database ⇒ Mongo::Database (readonly)
Returns database The database the client is operating on.
119 120 121 |
# File 'lib/mongo/client.rb', line 119 def database @database end |
#encrypter ⇒ Mongo::Crypt::AutoEncrypter (readonly)
Returns The object that encapsulates auto-encryption behavior.
126 127 128 |
# File 'lib/mongo/client.rb', line 126 def encrypter @encrypter end |
#options ⇒ Hash (readonly)
Returns options The configuration options.
122 123 124 |
# File 'lib/mongo/client.rb', line 122 def end |
Instance Method Details
#==(other) ⇒ true, false Also known as: eql?
Determine if this client is equivalent to another object.
155 156 157 158 |
# File 'lib/mongo/client.rb', line 155 def ==(other) return false unless other.is_a?(Client) cluster == other.cluster && == other. end |
#[](collection_name, options = {}) ⇒ Mongo::Collection
Get a collection object for the provided collection name.
172 173 174 |
# File 'lib/mongo/client.rb', line 172 def [](collection_name, = {}) database[collection_name, ] end |
#close ⇒ true
Close all connections.
753 754 755 756 757 758 |
# File 'lib/mongo/client.rb', line 753 def close @connect_lock.synchronize do do_close end true end |
#close_encrypter ⇒ true
Close encrypter and clean up auto-encryption resources.
763 764 765 766 767 |
# File 'lib/mongo/client.rb', line 763 def close_encrypter @encrypter.close if @encrypter true end |
#cluster_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.
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 |
# File 'lib/mongo/client.rb', line 501 def # 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 .reject do |key, value| CRUD_OPTIONS.include?(key.to_sym) end.merge( # but need to put the database back in for auth... database: [: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: [:max_read_retries], read_retry_interval: [:read_retry_interval], ).tap do || # 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. if cluster .update(srv_uri: cluster.[:srv_uri]) end end end |
#database_names(filter = {}, opts = {}) ⇒ Array<String>
Get the names of all databases.
804 805 806 |
# File 'lib/mongo/client.rb', line 804 def database_names(filter = {}, opts = {}) list_databases(filter, true, opts).collect{ |info| info['name'] } end |
#hash ⇒ Integer
Get the hash value of the client.
184 185 186 |
# File 'lib/mongo/client.rb', line 184 def hash [cluster, ].hash end |
#inspect ⇒ String
Get an inspection of the client as a string.
564 565 566 |
# File 'lib/mongo/client.rb', line 564 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.
820 821 822 823 824 825 |
# File 'lib/mongo/client.rb', line 820 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.
838 839 840 841 842 |
# File 'lib/mongo/client.rb', line 838 def list_mongo_databases(filter = {}, opts = {}) database_names(filter, opts).collect do |name| Database.new(self, name, ) end end |
#max_read_retries ⇒ Integer
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.
532 533 534 |
# File 'lib/mongo/client.rb', line 532 def max_read_retries [:max_read_retries] || Cluster::MAX_READ_RETRIES end |
#max_write_retries ⇒ Integer
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.
552 553 554 |
# File 'lib/mongo/client.rb', line 552 def max_write_retries [:max_write_retries] || Cluster::MAX_WRITE_RETRIES end |
#read_concern ⇒ Hash
Get the read concern for this client.
730 731 732 |
# File 'lib/mongo/client.rb', line 730 def read_concern [:read_concern] end |
#read_preference ⇒ BSON::Document
Get the read preference from the options passed to the client.
615 616 617 |
# File 'lib/mongo/client.rb', line 615 def read_preference @read_preference ||= [:read] end |
#read_retry_interval ⇒ Float
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.
542 543 544 |
# File 'lib/mongo/client.rb', line 542 def read_retry_interval [:read_retry_interval] || Cluster::READ_RETRY_INTERVAL end |
#reconnect ⇒ true
Reconnect the client.
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 |
# File 'lib/mongo/client.rb', line 777 def reconnect addresses = cluster.addresses.map(&:to_s) @connect_lock.synchronize do do_close rescue nil @cluster = Cluster.new(addresses, monitoring, ) if [:auto_encryption_options] build_encrypter end end true end |
#server_selector ⇒ Mongo::ServerSelector
Get the server selector. It either uses the read preference defined in the client options or defaults to a Primary server selector.
593 594 595 596 597 598 599 |
# File 'lib/mongo/client.rb', line 593 def server_selector @server_selector ||= if read_preference ServerSelector.get(read_preference) else ServerSelector.primary end end |
#start_session(options = {}) ⇒ Session
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.
863 864 865 866 |
# File 'lib/mongo/client.rb', line 863 def start_session( = {}) get_session(.merge(implicit: false)) or raise Error::InvalidSession.new(Session::SESSIONS_NOT_SUPPORTED) end |
#summary ⇒ String
This method is experimental and subject to change.
Get a summary of the client state.
579 580 581 |
# File 'lib/mongo/client.rb', line 579 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).
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 |
# File 'lib/mongo/client.rb', line 682 def () = ().tap do |opts| # Our options are frozen = .dup if [:write] && opts[:write_concern] .delete(:write) end if [:write_concern] && opts[:write] .delete(:write_concern) end .update(opts) = .freeze = [:auto_encryption_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 [:auto_encryption_options] && @connect_lock.synchronize do build_encrypter end elsif [:auto_encryption_options].nil? @connect_lock.synchronize do @encrypter = nil end end end end |
#use(name) ⇒ Mongo::Client
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.
634 635 636 |
# File 'lib/mongo/client.rb', line 634 def use(name) with(database: name) end |
#watch(pipeline = [], options = {}) ⇒ ChangeStream
A change stream only allows ‘majority’ read concern.
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.
901 902 903 904 905 906 907 908 909 |
# File 'lib/mongo/client.rb', line 901 def watch(pipeline = [], = {}) return use(Database::ADMIN).watch(pipeline, ) unless database.name == Database::ADMIN Mongo::Collection::View::ChangeStream.new( Mongo::Collection::View.new(self["#{Database::COMMAND}.aggregate"]), pipeline, Mongo::Collection::View::ChangeStream::CLUSTER, ) end |
#with(new_options = Options::Redacted.new) ⇒ Mongo::Client
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.
656 657 658 659 660 661 662 663 664 665 666 |
# File 'lib/mongo/client.rb', line 656 def with( = Options::Redacted.new) clone.tap do |client| opts = client.() Database.create(client) # We can't use the same cluster if some options that would affect it # have changed. if (opts) Cluster.create(client) end end end |
#write_concern ⇒ Mongo::WriteConcern
Get the write concern for this client. If no option was provided, then a default single server acknowledgement will be used.
744 745 746 |
# File 'lib/mongo/client.rb', line 744 def write_concern @write_concern ||= WriteConcern.get([:write_concern] || [:write]) end |