Package com.mongodb

Class MongoClientURI



  • public class MongoClientURI
    extends Object
    Represents a URI which can be used to create a MongoClient instance. The URI describes the hosts to be used and options.

    The format of the URI 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 well
    • host1 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 the jnr.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 the username:password@ syntax is used. If not specified the "admin" database will be used by default.
    • ?options are connection options. Note that if database is absent there is still a / required between the last host and the ? introducing the 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 well
    • host 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 "_mongodb._tcp". 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 the username:password@ syntax is used. If not specified the "admin" database will be used by default.
    • ?options are connection options. Note that if database is absent there is still a / required between the last host and the ? introducing the 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.

    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 SSL.
    • sslInvalidHostNameAllowed=true|false: Whether to allow invalid host names for SSL connections.
    • connectTimeoutMS=ms: How long a connection can take to be opened before timing out.
    • socketTimeoutMS=ms: How long a send or receive on a socket can take before timing out.
    • maxIdleTimeMS=ms: Maximum idle time of a pooled connection. A connection that exceeds this limit will be closed
    • maxLifeTimeMS=ms: Maximum life time of a pooled connection. A connection that exceeds this limit will be closed

    Connection pool configuration:

    • maxPoolSize=n: The maximum number of connections in the connection pool.
    • waitQueueMultiple=n : this multiplier, multiplied with the maxPoolSize setting, gives the maximum number of threads that may be waiting for a connection to become available from the pool. All further threads will get an exception right away.
    • waitQueueTimeoutMS=ms: The maximum wait time in milliseconds that a thread may wait for a connection to become available.

    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 also w and wtimeoutMS).
      • 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"
    • wtimeoutMS=ms
      • The driver adds { wtimeout : ms } to all write commands. Implies safe=true.
      • Used in combination with w
    • retryWrites=true|false. If true the driver will retry supported write operations if they fail due to a network error. Defaults to false.

    Read preference configuration:

    • slaveOk=true|false: Whether a driver connected to a replica set will send reads to slaves/secondaries.
    • readPreference=enum: The read preference for this connection. If set, it overrides any slaveOk value.
      • Enumerated values:
        • primary
        • primaryPreferred
        • secondary
        • secondaryPreferred
        • nearest
    • 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 isMaster 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: 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 and MONGODB-X509 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 URI. 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).
    • gssapiServiceName=string: This option only applies to the GSSAPI mechanism and is used to alter the service name..

    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' and 'snappy'.
    • 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.

    Note: This class is a replacement for MongoURI, to be used with MongoClient. The main difference in behavior is that the default write concern is WriteConcern.ACKNOWLEDGED.

    Since:
    2.10.0
    See Also:
    for the default values for all options
    MongoDB documentation
    Connection String URI Format
    • Constructor Detail

      • MongoClientURI

        public MongoClientURI​(String uri)
        Creates a MongoURI from the given string.
        Parameters:
        uri - the URI
      • MongoClientURI

        public MongoClientURI​(String uri,
                              MongoClientOptions.Builder builder)
        Creates a MongoURI from the given URI string, and MongoClientOptions.Builder. The builder can be configured with default options, which may be overridden by options specified in the URI string.

        The MongoClientURI takes ownership of the MongoClientOptions.Builder instance that is passed to this constructor, and may modify it.

        Parameters:
        uri - the URI
        builder - a non-null Builder, which may be modified within this constructor,
        Since:
        2.11.0
    • Method Detail

      • getUsername

        @Nullable
        public String getUsername​()
        Gets the username
        Returns:
        the username
      • getPassword

        @Nullable
        public char[] getPassword​()
        Gets the password
        Returns:
        the password
      • getHosts

        public List<String> getHosts​()
        Gets the list of hosts
        Returns:
        the host list
      • getDatabase

        @Nullable
        public String getDatabase​()
        Gets the database name
        Returns:
        the database name
      • getCollection

        @Nullable
        public String getCollection​()
        Gets the collection name
        Returns:
        the collection name
      • getURI

        public String getURI​()
        Get the unparsed URI.
        Returns:
        the URI
      • getOptions

        public MongoClientOptions getOptions​()
        Gets the options
        Returns:
        the MongoClientOptions based on this URI.
      • hashCode

        public int hashCode​()
        Overrides:
        hashCode in class Object