Class ConnectionString
Represents a Connection String. The Connection String describes the hosts to be used and options.
The format of the Connection String is:
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database.collection][?options]]
mongodb://
is a required prefix to identify that this is a string in the standard connection format.username:password@
are optional. If given, the driver will attempt to login to a database after connecting to a database server. For some authentication mechanisms, only the username is specified and the password is not, in which case the ":" after the username is left off as wellhost1
is the only required part of the connection string. It identifies a server address to connect to. Support for Unix domain sockets was added in 3.7. Note: The path must be urlencoded eg:mongodb://%2Ftmp%2Fmongodb-27017.sock
and thejnr.unixsocket
library installed.:portX
is optional and defaults to :27017 if not provided./database
is the name of the database to login to and thus is only relevant if theusername:password@
syntax is used. If not specified the "admin" database will be used by default.?options
are connection options. Options are name=value pairs and the pairs are separated by "&". For backwards compatibility, ";" is accepted as a separator in addition to "&", but should be considered as deprecated.
An alternative format, using the mongodb+srv protocol, is:
mongodb+srv://[username:password@]host[/[database][?options]]
mongodb+srv://
is a required prefix for this format.username:password@
are optional. If given, the driver will attempt to login to a database after connecting to a database server. For some authentication mechanisms, only the username is specified and the password is not, in which case the ":" after the username is left off as wellhost
is the only required part of the URI. It identifies a single host name for which SRV records are looked up from a Domain Name Server after prefixing the host name with, by default,"_mongodb._tcp"
("mongodb"
is the default SRV service name, but can be replaced via thesrvServiceName
query parameter), The host/port for each SRV record becomes the seed list used to connect, as if each one were provided as host/port pair in a URI using the normal mongodb protocol./database
is the name of the database to login to and thus is only relevant if theusername:password@
syntax is used. If not specified the "admin" database will be used by default.?options
are connection options. Options are name=value pairs and the pairs are separated by "&". For backwards compatibility, ";" is accepted as a separator in addition to "&", but should be considered as deprecated. Additionally with the mongodb+srv protocol, TXT records are looked up from a Domain Name Server for the given host, and the text value of each one is prepended to any options on the URI itself. Because the last specified value for any option wins, that means that options provided on the URI will override any that are provided via TXT records.
The following options are supported (case insensitive):
Server Selection Configuration:
serverSelectionTimeoutMS=ms
: How long the driver will wait for server selection to succeed before throwing an exception.localThresholdMS=ms
: When choosing among multiple MongoDB servers to send a request, the driver will only send that request to a server whose ping time is less than or equal to the server with the fastest ping time plus the local threshold.
Server Monitoring Configuration:
heartbeatFrequencyMS=ms
: The frequency that the driver will attempt to determine the current state of each server in the cluster.serverMonitoringMode=enum
: The server monitoring mode, which defines the monitoring protocol to use. Enumerated values:stream
;poll
;auto
- the default.
Replica set configuration:
replicaSet=name
: Implies that the hosts given are a seed list, and the driver will attempt to find all members of the set.
Connection Configuration:
ssl=true|false
: Whether to connect using TLS.tls=true|false
: Whether to connect using TLS. Supersedes the ssl optiontlsInsecure=true|false
: If connecting with TLS, this option enables insecure TLS connections. Currently this has the same effect of setting tlsAllowInvalidHostnames to true. Other mechanism for relaxing TLS security constraints must be handled in the application by customizing theSSLContext
sslInvalidHostNameAllowed=true|false
: Whether to allow invalid host names for TLS connections.tlsAllowInvalidHostnames=true|false
: Whether to allow invalid host names for TLS connections. Supersedes the sslInvalidHostNameAllowed optiontimeoutMS=ms
: Time limit for the full execution of an operation. Note: This parameter is part of an Alpha API and may be subject to changes or even removal in future releases.connectTimeoutMS=ms
: How long a connection can take to be opened before timing out.socketTimeoutMS=ms
: How long a receive on a socket can take before timing out. This option is the same asSocketSettings.getReadTimeout(TimeUnit)
. Deprecated, usetimeoutMS
instead.maxIdleTimeMS=ms
: Maximum idle time of a pooled connection. A connection that exceeds this limit will be closedmaxLifeTimeMS=ms
: Maximum life time of a pooled connection. A connection that exceeds this limit will be closed
Proxy Configuration:
proxyHost=string
: The SOCKS5 proxy host to establish a connection through. It can be provided as a valid IPv4 address, IPv6 address, or a domain name. Required if either proxyPassword, proxyUsername or proxyPort are specifiedproxyPort=n
: The port number for the SOCKS5 proxy server. Must be a non-negative integer.proxyUsername=string
: Username for authenticating with the proxy server. Required if proxyPassword is specified.proxyPassword=string
: Password for authenticating with the proxy server. Required if proxyUsername is specified.
Connection pool configuration:
maxPoolSize=n
: The maximum number of connections in the connection pool.minPoolSize=n
: The minimum number of connections in the connection pool.waitQueueTimeoutMS=ms
: The maximum duration to wait until either: an in-use connection becomes available, or a connection is created and begins to be established. SeegetMaxWaitTime()
for more details. . Deprecated, usetimeoutMS
instead.maxConnecting=n
: The maximum number of connections a pool may be establishing concurrently.
Write concern configuration:
safe=true|false
true
: the driver ensures that all writes are acknowledged by the MongoDB server, or else throws an exception. (see alsow
andwtimeoutMS
).false
: the driver does not ensure that all writes are acknowledged by the MongoDB server.
journal=true|false
true
: the driver waits for the server to group commit to the journal file on disk.false
: the driver does not wait for the server to group commit to the journal file on disk.
w=wValue
- The driver adds { w : wValue } to all write commands. Implies
safe=true
. - wValue is typically a number, but can be any string in order to allow for specifications like
"majority"
- The driver adds { w : wValue } to all write commands. Implies
wtimeoutMS=ms
- The driver adds { wtimeout : ms } to all write commands. Implies
safe=true
. - Used in combination with
w
. Deprecated, usetimeoutMS
instead
- The driver adds { wtimeout : ms } to all write commands. Implies
Read preference configuration:
readPreference=enum
: The read preference for this connection.- Enumerated values:
primary
primaryPreferred
secondary
secondaryPreferred
nearest
- Enumerated values:
readPreferenceTags=string
. A representation of a tag set as a comma-separated list of colon-separated key-value pairs, e.g."dc:ny,rack:1
". Spaces are stripped from beginning and end of all keys and values. To specify a list of tag sets, using multiple readPreferenceTags, e.g.readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags=
- Note the empty value for the last one, which means match any secondary as a last resort.
- Order matters when using multiple readPreferenceTags.
maxStalenessSeconds=seconds
. The maximum staleness in seconds. For use with any non-primary read preference, the driver estimates the staleness of each secondary, based on lastWriteDate values provided in server hello responses, and selects only those secondaries whose staleness is less than or equal to maxStalenessSeconds. Not providing the parameter or explicitly setting it to -1 indicates that there should be no max staleness check. The maximum staleness feature is designed to prevent badly-lagging servers from being selected. The staleness estimate is imprecise and shouldn't be used to try to select "up-to-date" secondaries. The minimum value is either 90 seconds, or the heartbeat frequency plus 10 seconds, whichever is greatest.
Authentication configuration:
authMechanism=MONGO-CR|GSSAPI|PLAIN|MONGODB-X509|MONGODB-OIDC
: The authentication mechanism to use if a credential was supplied. The default is unspecified, in which case the client will pick the most secure mechanism available based on the sever version. For the GSSAPI, MONGODB-X509, and MONGODB-OIDC mechanisms, no password is accepted, only the username.authSource=string
: The source of the authentication credentials. This is typically the database that the credentials have been created. The value defaults to the database specified in the path portion of the connection string. If the database is specified in neither place, the default value is "admin". This option is only respected when using the MONGO-CR mechanism (the default).authMechanismProperties=PROPERTY_NAME:PROPERTY_VALUE,PROPERTY_NAME2:PROPERTY_VALUE2
: This option allows authentication mechanism properties to be set on the connection string.gssapiServiceName=string
: This option only applies to the GSSAPI mechanism and is used to alter the service name. Deprecated, please useauthMechanismProperties=SERVICE_NAME:string
instead.
Server Handshake configuration:
appName=string
: Sets the logical name of the application. The application name may be used by the client to identify the application to the server, for use in server logs, slow query logs, and profile collection.
Compressor configuration:
compressors=string
: A comma-separated list of compressors to request from the server. The supported compressors currently are 'zlib', 'snappy' and 'zstd'.zlibCompressionLevel=integer
: Integer value from -1 to 9 representing the zlib compression level. Lower values will make compression faster, while higher values will make compression better.
SRV configuration:
srvServiceName=string
: The SRV service name. SeeClusterSettings.getSrvServiceName()
for details.srvMaxHosts=number
: The maximum number of hosts from the SRV record to connect to.
General configuration:
retryWrites=true|false
. If true the driver will retry supported write operations if they fail due to a network error. Defaults to true.retryReads=true|false
. If true the driver will retry supported read operations if they fail due to a network error. Defaults to true.uuidRepresentation=unspecified|standard|javaLegacy|csharpLegacy|pythonLegacy
. SeeMongoClientSettings.getUuidRepresentation()
for documentation of semantics of this parameter. Defaults to "javaLegacy", but will change to "unspecified" in the next major release.directConnection=true|false
. If true the driver will set the connection to be a direct connection to the host.loadBalanced=true|false
. If true the driver will assume that it's connecting to MongoDB through a load balancer.
- Since:
- 3.0.0
- MongoDB documentation
- Connection String Format
-
Constructor Summary
ConstructorDescriptionConnectionString
(String connectionString) Creates a ConnectionString from the given string.ConnectionString
(String connectionString, DnsClient dnsClient) Creates a ConnectionString from the given string with the givenDnsClient
. -
Method Summary
Modifier and TypeMethodDescriptionboolean
Gets the logical name of the application.Gets the collection nameGets the list of compressors.Get the unparsed connection string.Gets the socket connect timeout specified in the connection string.Gets the credential or null if no credentials were specified in the connection string.Gets the database namegetHosts()
Gets the list of hostsGets the maximum number of connections a pool may be establishing concurrently specified in the connection string.Gets the maximum connection idle time specified in the connection string.Gets the maximum connection lifetime specified in the connection string.Gets the maximum connection pool size specified in the connection string.The maximum duration to wait until either: an in-use connection becomes available; or a connection is created and begins to be established.Gets the minimum connection pool size specified in the connection string.char[]
Gets the passwordGets the SOCKS5 proxy host specified in the connection string.Gets the SOCKS5 proxy password specified in the connection string.Gets the SOCKS5 proxy port specified in the connection string.Gets the SOCKS5 proxy username specified in the connection string.Gets the read concern specified in the connection string.Gets the read preference specified in the connection string.Gets the required replica set name specified in the connection string.Gets whether reads should be retried if they fail due to a network errorGets whether writes should be retried if they fail due to a network errorThe server monitoring mode, which defines the monitoring protocol to use.Gets the socket timeout specified in the connection string.Gets the maximum number of hosts to connect to when using SRV protocol.Gets the SRV service name.Gets the SSL enabled value specified in the connection string.Gets the SSL invalidHostnameAllowed value specified in the connection string.The time limit for the full execution of an operation in milliseconds.Gets the usernameGets the UUID representation.Gets the write concern specified in the connection string.int
hashCode()
Indicates if the connection should be a direct connectionIndicates if the connection is through a load balancer.boolean
Returns true if the connection string requires SRV protocol to resolve the host lists from the configured host.toString()
-
Constructor Details
-
ConnectionString
Creates a ConnectionString from the given string.- Parameters:
connectionString
- the connection string- Since:
- 3.0
-
ConnectionString
Creates a ConnectionString from the given string with the givenDnsClient
.If setting
MongoClientSettings.getDnsClient()
explicitly, care should be taken to call this constructor with the sameDnsClient
.- Parameters:
connectionString
- the connection stringdnsClient
- the DNS client with which to resolve TXT record for the mongodb+srv protocol- Since:
- 4.10
- See Also:
-
-
Method Details
-
getUsername
Gets the username- Returns:
- the username
-
getPassword
Gets the password- Returns:
- the password
-
isSrvProtocol
public boolean isSrvProtocol()Returns true if the connection string requires SRV protocol to resolve the host lists from the configured host.- Returns:
- true if SRV protocol is required to resolve hosts.
-
getSrvMaxHosts
Gets the maximum number of hosts to connect to when using SRV protocol.- Returns:
- the maximum number of hosts to connect to when using SRV protocol. Defaults to null.
- Since:
- 4.4
-
getSrvServiceName
Gets the SRV service name.- Returns:
- the SRV service name. Defaults to null in the connection string, but defaults to
"mongodb"
inClusterSettings
. - Since:
- 4.5
- See Also:
-
getHosts
Gets the list of hosts- Returns:
- the host list
-
getDatabase
Gets the database name- Returns:
- the database name
-
getCollection
Gets the collection name- Returns:
- the collection name
-
isDirectConnection
Indicates if the connection should be a direct connection- Returns:
- true if a direct connection
- Since:
- 4.1
-
isLoadBalanced
Indicates if the connection is through a load balancer.- Returns:
- true if a load-balanced connection
- Since:
- 4.3
-
getConnectionString
Get the unparsed connection string.- Returns:
- the connection string
- Since:
- 3.1
-
getCredential
Gets the credential or null if no credentials were specified in the connection string.- Returns:
- the credentials in an immutable list
- Since:
- 3.6
-
getReadPreference
Gets the read preference specified in the connection string.- Returns:
- the read preference
-
getReadConcern
Gets the read concern specified in the connection string.- Returns:
- the read concern
-
getWriteConcern
Gets the write concern specified in the connection string.- Returns:
- the write concern
-
getRetryWritesValue
Gets whether writes should be retried if they fail due to a network error
The name of this method differs from others in this class so as not to conflict with the now removed getRetryWrites() method, which returned a primitiveboolean
value, and didn't allow callers to differentiate between a false value and an unset value.- Returns:
- the retryWrites value, or null if unset
- Since:
- 3.9
- Since server release
- 3.6
-
getRetryReads
Gets whether reads should be retried if they fail due to a network error
- Returns:
- the retryWrites value
- Since:
- 3.11
- Since server release
- 3.6
-
getMinConnectionPoolSize
Gets the minimum connection pool size specified in the connection string.- Returns:
- the minimum connection pool size
-
getMaxConnectionPoolSize
Gets the maximum connection pool size specified in the connection string.- Returns:
- the maximum connection pool size
- See Also:
-
getMaxWaitTime
The maximum duration to wait until either:- an in-use connection becomes available; or
-
a connection is created and begins to be established.
The time between requesting a connection
and it being created is limited by this maximum duration.
The maximum time between it being created and successfully checked out,
which includes the time to establish the created connection,
is affected by
SocketSettings.getConnectTimeout(TimeUnit)
,SocketSettings.getReadTimeout(TimeUnit)
among others, and is not affected by this maximum duration.
-
the number of connections per pool is limited by
getMaxConnectionPoolSize()
; -
the number of connections a pool may be establishing concurrently is limited by
getMaxConnecting()
.
- Returns:
- The value of the
waitQueueTimeoutMS
option, if specified. - See Also:
-
getMaxConnectionIdleTime
Gets the maximum connection idle time specified in the connection string.- Returns:
- the maximum connection idle time
-
getMaxConnectionLifeTime
Gets the maximum connection lifetime specified in the connection string.- Returns:
- the maximum connection lifetime
-
getMaxConnecting
Gets the maximum number of connections a pool may be establishing concurrently specified in the connection string.- Returns:
- The maximum number of connections a pool may be establishing concurrently
if the
maxConnecting
option is specified in the connection string, ornull
otherwise. - Since:
- 4.4
- See Also:
-
getTimeout
The time limit for the full execution of an operation in milliseconds.If set the following deprecated options will be ignored:
waitQueueTimeoutMS
,socketTimeoutMS
,wTimeoutMS
,maxTimeMS
andmaxCommitTimeMS
null
means that the timeout mechanism for operations will defer to using:waitQueueTimeoutMS
: The maximum wait time in milliseconds that a thread may wait for a connection to become availablesocketTimeoutMS
: How long a send or receive on a socket can take before timing out.wTimeoutMS
: How long the server will wait for the write concern to be fulfilled before timing out.maxTimeMS
: The cumulative time limit for processing operations on a cursor. See: cursor.maxTimeMS.maxCommitTimeMS
: The maximum amount of time to allow a singlecommitTransaction
command to execute. See:TransactionOptions.getMaxCommitTime(java.util.concurrent.TimeUnit)
.
0
means infinite timeout.> 0
The time limit to use for the full execution of an operation.
- Returns:
- the time limit for the full execution of an operation in milliseconds or null.
- Since:
- 5.2
-
getConnectTimeout
Gets the socket connect timeout specified in the connection string.- Returns:
- the socket connect timeout
-
getSocketTimeout
Gets the socket timeout specified in the connection string.- Returns:
- the socket timeout
-
getSslEnabled
Gets the SSL enabled value specified in the connection string.- Returns:
- the SSL enabled value
-
getProxyHost
Gets the SOCKS5 proxy host specified in the connection string.- Returns:
- the proxy host value.
- Since:
- 4.11
-
getProxyPort
Gets the SOCKS5 proxy port specified in the connection string.- Returns:
- the proxy port value.
- Since:
- 4.11
-
getProxyUsername
Gets the SOCKS5 proxy username specified in the connection string.- Returns:
- the proxy username value.
- Since:
- 4.11
-
getProxyPassword
Gets the SOCKS5 proxy password specified in the connection string.- Returns:
- the proxy password value.
- Since:
- 4.11
-
getSslInvalidHostnameAllowed
Gets the SSL invalidHostnameAllowed value specified in the connection string.- Returns:
- the SSL invalidHostnameAllowed value
- Since:
- 3.3
-
getRequiredReplicaSetName
Gets the required replica set name specified in the connection string.- Returns:
- the required replica set name
-
getServerSelectionTimeout
- Returns:
- the server selection timeout (in milliseconds), or null if unset
- Since:
- 3.3
-
getLocalThreshold
- Returns:
- the local threshold (in milliseconds), or null if unset since 3.3
-
getHeartbeatFrequency
- Returns:
- the heartbeat frequency (in milliseconds), or null if unset since 3.3
-
getServerMonitoringMode
The server monitoring mode, which defines the monitoring protocol to use.Default is
ServerMonitoringMode.AUTO
.- Returns:
- The
ServerMonitoringMode
, ornull
if unset and the default is to be used. - Since:
- 5.1
- See Also:
-
getApplicationName
Gets the logical name of the application. The application name may be used by the client to identify the application to the server, for use in server logs, slow query logs, and profile collection.Default is null.
- Returns:
- the application name, which may be null
- Since:
- 3.4
- Since server release
- 3.4
-
getCompressorList
Gets the list of compressors.- Returns:
- the non-null list of compressors
- Since:
- 3.6
-
getUuidRepresentation
Gets the UUID representation.Default is null.
- Returns:
- the UUID representation, which may be null if it was unspecified
- Since:
- 3.12
-
toString
-
equals
-
hashCode
public int hashCode()
-