Navigation

Connection String URI Format

This document describes the URI formats for defining connections between applications and MongoDB instances in the official MongoDB drivers. For a list of drivers and links to driver documentation, see drivers.

Connection String Formats

You can specify the MongoDB connection string using either:

Standard Connection String Format

This section describes the standard format of the MongoDB connection URI used to connect to a MongoDB deployment: standalone, replica set, or a sharded cluster.

The standard URI connection scheme has the form:

mongodb://[username:password@]host1[:port1][,...hostN[:portN]]][/[database][?options]]

Examples

  • For a standalone:

    mongodb://mongodb0.example.com:27017/admin
    
  • For a standalone that enforces access control:

    mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017/admin
    

    If the username or password includes the at sign @, colon :, slash /, or the percent sign % character, use percent encoding.

Note

For a replica set, specify the hostname(s) of the mongod instance(s) as listed in the replica set configuration.

For a replica set, include the replicaSet option.

  • For a replica set:

    mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/admin?replicaSet=myRepl
    
  • For a replica set that enforces access control, include user credentials:

    mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/admin?replicaSet=myRepl
    

    If the username or password includes the at sign @, colon :, slash /, or the percent sign % character, use percent encoding.

Note

For a connection string to a sharded cluster, specify mongos hosts in the connection string.

  • For a sharded cluster:

    mongodb://mongos0.example.com:27017,mongos1.example.com:27017,mongos2.example.com:27017/admin
    
  • For a sharded cluster that enforces access control, include user credentials:

    mongodb://myDBReader:D1fficultP%40ssw0rd@mongos0.example.com:27017,mongos1.example.com:27017,mongos2.example.com:27017/admin
    

    If the username or password includes the at sign @, colon :, slash /, or the percent sign % character, use percent encoding.

For more examples, see Examples.

Components

The standard URI connection string includes the following components:

Component Description
mongodb:// A required prefix to identify that this is a string in the standard connection format.
username:password@

Optional. Authentication credentials. If specified, the client will attempt to log in to the specific database using these credentials after connecting.

If the username or password includes the at sign @, colon :, slash /, or the percent sign % character, use percent encoding.

See also authSource.

host[:port]

The host (and optional port number) where the mongod instance (or mongos instance for a sharded cluster) is running. You can specify a hostname, IP address, or UNIX domain socket. Specify as many hosts as appropriate for your deployment topology:

  • For a standalone, specify the hostname of the standalone mongod instance.
  • For a replica set, specify the hostname(s) of the mongod instance(s) as listed in the replica set configuration.
  • For a sharded cluster, specify the hostname(s) of the mongos instance(s).

If the port number is not specified, the default port 27017 is used.

/database Optional. The name of the database to authenticate if the connection string includes authentication credentials in the form of username:password@. If /database is not specified and the connection string includes credentials, the driver will authenticate to the admin database. See also authSource.
?<options>

Optional. A query string that specifies connection specific options as <name>=<value> pairs. See Connection String Options for a full description of these options.

If the connection string does not specify a database/ you must specify a slash (/) between the last host and the question mark (?) that begins the string of options.

DNS Seedlist Connection Format

New in version 3.6.

In addition to the standard connection format, MongoDB supports a DNS-constructed seed list. Using DNS to construct the available servers list allows more flexibility of deployment and the ability to change the servers in rotation without reconfiguring clients.

In order to leverage the DNS seedlist, use a connection string prefix of mongodb+srv: rather than the standard mongodb:. The +srv indicates to the client that the hostname that follows corresponds to a DNS SRV record. The driver or mongo shell will then query the DNS for the record to determine which hosts are running the mongod instances.

Note

Use of the +srv connection string modifier automatically sets the ssl option to true for the connection. You can override this behavior by explicitly setting the ssl option to false with ssl=false in the query string.

The following example shows a typical connection string for a DNS seedlist connection string:

mongodb+srv://server.example.com/

The corresponding DNS configuration might resemble:

Record                            TTL   Class    Priority Weight Port  Target
_mongodb._tcp.server.example.com. 86400 IN SRV   0        5      27317 mongodb1.example.com.
_mongodb._tcp.server.example.com. 86400 IN SRV   0        5      27017 mongodb2.example.com.

Important

The hostnames returned in SRV records must share the same parent domain (in this example, example.com) as the given hostname. If the parent domains and hostname do not match, you will not be able to connect.

Like the standard connection string, the DNS seedlist connection string supports specifying options as a query string. With a DNS seedlist connection string, you can also specify the following options via a TXT record:

  • replicaSet
  • authSource

You may only specify one TXT record per mongod instance. If multiple TXT records appear in the DNS and/or if the TXT record contains an option other than replicaSet or authSource, the client will return an error.

The TXT record for the server.example.com DNS entry would resemble:

Record              TTL   Class    Text
server.example.com. 86400 IN TXT   "replicaSet=mySet&authSource=authDB"

Taken together, the DNS SRV records and the options specified in the TXT record resolve to the following standard format connection string:

mongodb://mongodb1.example.com:27317,mongodb2.example.com:27017/?replicaSet=mySet&authSource=authDB

You can override the options specified in a TXT record by passing the option in the query string. In the following example, the query string has provided an override for the authSource option configured in the TXT record of the DNS entry above.

mongodb+srv://server.example.com/?connectTimeoutMS=300000&authSource=aDifferentAuthDB

Given the override for the authSource, the equivalent connection string in the standard format would be:

mongodb://mongodb1.example.com:27317,mongodb2.example.com:27017/?connectTimeoutMS=300000&replicaSet=mySet&authSource=aDifferentAuthDB

Note

The mongodb+srv option will fail if there is no available DNS with records that correspond to the hostname identified in the connection string. In addition, use of the +srv connection string modifier automatically sets the ssl option to true for the connection. You can override this behavior by explicitly setting the ssl option to false with ssl=false in the query string.

See

Connect to a Replica Set Using the DNS Seedlist Connection Format provides an example of connecting the mongo shell to a replica set using the DNS Seedlist Connection Format.

Connection String Options

This section lists all connection options.

Connection options are pairs in the following form: name=value. The value is always case sensitive. Separate options with the ampersand (i.e. &) character. In the following example, a connection includes the replicaSet and connectTimeoutMS options:

mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test&connectTimeoutMS=300000

Semi-colon separator for connection string arguments

To provide backwards compatibility, drivers currently accept semi-colons (i.e. ;) as option separators.

Replica Set Option

The following connection string to a replica set named myRepl with members running on the specified hosts:

mongodb://db0.example.com:27017,db1.example.com:27017,db2.example.com:27017/admin?replicaSet=myRepl
Connection Option Description
replicaSet

Specifies the name of the replica set, if the mongod is a member of a replica set.

When connecting to a replica set, provide a seed list of the replica set member(s) to the host[:port] component of the uri. For specific details, refer to your driver documentation.

Connection Options

The following connection string to a replica set includes ssl=true option:

mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&ssl=true
Connection Option Description
ssl

A boolean to enable or disables TLS/SSL for the connection:

connectTimeoutMS
The time in milliseconds to attempt a connection before timing out. The default is never to timeout, though different drivers might vary. See the driver documentation.
socketTimeoutMS
The time in milliseconds to attempt a send or receive on a socket before the attempt times out. The default is never to timeout, though different drivers might vary. See the driver documentation.
compressors

Comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance.

You can specify the following compressors:

  • snappy
  • zlib (Available in MongoDB 3.6 or greater)

If you specify multiple compressors, then the order in which you list the compressors matter as well as the communication initiator. For example, if the client specifies the following network compressors "zlib,snappy" and the mongod specifies "snappy,zlib", messages between the client and the mongod uses zlib.

Important

Messages are compressed when both parties enable network compression. Otherwise, messages between the parties are uncompressed.

If the parties do not share at least one common compressor, messages between the parties are uncompressed.

Starting in MongoDB 4.0.5 (and MongoDB 3.6.10), the mongo shell supports the uri connection string option compressors.

zlibCompressionLevel

An integer that specifies the compression level if using zlib for network compression.

You can specify an integer value ranging from -1 to 9:

Value Notes
-1 Default compression level, usually level 6 compression.
0 No compression
1 - 9

Increasing level of compression but at the cost of speed, with:

  • 1 providing the best speed but least compression, and
  • 9 providing the best compression but at the slowest speed.

Not supported by the mongo shell.

Connection Pool Options

Most drivers implement some kind of connection pool handling. Some drivers do not support connection pools. See your driver documentation for more information on the connection pooling implementation. These options allow applications to configure the connection pool when connecting to the MongoDB deployment.

Connection Option Description
maxPoolSize
The maximum number of connections in the connection pool. The default value is 100.
minPoolSize

The minimum number of connections in the connection pool. The default value is 0.

Note

The minPoolSize option is not supported by all drivers. For information on your driver, see the drivers documentation.

maxIdleTimeMS

The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed.

This option is not supported by all drivers.

waitQueueMultiple

A number that the driver multiples the maxPoolSize value to, to provide the maximum number of threads allowed to wait for a connection to become available from the pool. For default values, see the /drivers documentation.

This option is not supported by all drivers.

waitQueueTimeoutMS

The maximum time in milliseconds that a thread can wait for a connection to become available. For default values, see the /drivers documentation.

This option is not supported by all drivers.

Write Concern Options

Write concern describes the kind of assurances that the mongod and the driver provide to the application regarding the success and durability of the write operation. For a full explanation of write concern and write operations in general, see Write Concern.

Note

You can specify the write concern both in the connection string and as a parameter to method calls like insert or update. If the write concern is specified in both places, the method parameter overrides the connection-string setting.

Connection Option Description
w

Corresponds to the write concern w Option. The w option requests acknowledgement that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags.

You can specify a number, the string majority, or a tag set.

For details, see w Option.

wtimeoutMS

Corresponds to the write concern wtimeout. wtimeoutMS specifies a time limit, in milliseconds, for the write concern.

When wtimeoutMS is 0, write operations will never time out. For more information, see wtimeout.

journal

Corresponds to the write concern j Option option. The journal option requests acknowledgement from MongoDB that the write operation has been written to the journal. For details, see j Option.

If you set journal to true, and specify a w value less than 1, journal prevails.

If you set journal to true, and the mongod does not have journaling enabled, as with storage.journal.enabled, then MongoDB will error.

readConcern Options

New in version 3.2: For the WiredTiger storage engine, MongoDB 3.2 introduces the readConcern option for replica sets and replica set shards.

Read Concern allows clients to choose a level of isolation for their reads from replica sets.

The following connection string to a replica set specifies readConcernLevel=majority:

mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&readConcernLevel=majority
Connection Option Description
readConcernLevel

The level of isolation. Can accept one of the following values:

For details, see Read Concern.

This connection string option is not available for the mongo shell. Specify the read concern as an option to the specific operation.

Read Preference Options

Read preferences describe the behavior of read operations with regards to replica sets. These parameters allow you to specify read preferences on a per-connection basis in the connection string.

For example:

  • The following connection string to a replica set specifies secondary read preference mode and a maxStalenessSeconds value of 120 seconds:

    mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&readPreference=secondary&maxStalenessSeconds=120
    
  • The following connection string to a sharded cluster specifies secondary read preference mode and a maxStalenessSeconds value of 120 seconds:

    mongodb://mongos1.example.com,mongos2.example.com/?readPreference=secondary&maxStalenessSeconds=120
    
  • The following connection string to a sharded cluster specifies secondary read preference mode as well as two readPreferenceTags:

    mongodb://mongos1.example.com,mongos2.example.com/?readPreference=secondary&readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:ny
    

Order matters when using multiple readPreferenceTags.

Connection Option Description
readPreference

Specifies the read preferences for this connection. Possible values are:

Multi-document transactions that contain read operations must use read preference primary.

All operations in a given transaction must route to the same member.

This connection string option is not available for the mongo shell. See cursor.readPref() and Mongo.setReadPref() instead.

maxStalenessSeconds

Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. For details, see maxStalenessSeconds.

By default, there is no maximum staleness and clients will not consider a secondary’s lag when choosing where to direct a read operation.

The minimum maxStalenessSeconds value is 90 seconds. Specifying a value between 0 and 90 seconds will produce an error. MongoDB drivers treat a maxStalenessSeconds value of -1 as “no max staleness”, the same as if maxStalenessSeconds is omitted.

Important

To use maxStalenessSeconds, all of the MongoDB instances in your deployment must be using MongoDB 3.4 or later. If any instances are on an earlier version of MongoDB, the driver or mongod/mongos will raise an error.

New in version 3.4.

readPreferenceTags

Specifies a tag set as a comma-separated list of colon-separated key-value pairs. For example, readPreferenceTags=dc:ny,rack:1.

To specify a list of tag sets, use multiple readPreferenceTags. Order matters when using multiple readPreferenceTags.

This connection string option is not available for the mongo shell. See cursor.readPref() and Mongo.setReadPref() instead.

Authentication Options

The following connection string to a replica set specifies the authSource to the admin database. That is the user credentials are authenticated to the admin database.

mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/test?replicaSet=myRepl&authSource=admin

If the username or password includes the at sign @, colon :, slash /, or the percent sign % characters, use percent encoding.

Connection Option Description
authSource

Specify the database name associated with the user’s credentials. authSource defaults to the database specified in the connection string.

For authentication mechanisms that delegate credential storage to other services, the authSource value should be $external as with the PLAIN (LDAP) and GSSAPI (Kerberos) authentication mechanisms.

MongoDB will ignore authSource values if the connection string specifies no username.

authMechanism

Specify the authentication mechanism that MongoDB will use to authenticate the connection. Possible values include:

MongoDB 4.0 removes support for the MONGODB-CR authentication mechanism. You cannot specify MONGODB-CR as the authentication mechanism when connecting to MongoDB 4.0+ deployments.

Only MongoDB Enterprise mongod and mongos instances provide GSSAPI (Kerberos) and PLAIN (LDAP) mechanisms. To use MONGODB-X509, you must have TLS/SSL Enabled.

See Authentication for more information about the authentication system in MongoDB. Also consider Use x.509 Certificates to Authenticate Clients for more information on x509 authentication.

authMechanismProperties

Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs.

Possible key-value pairs are:

SERVICE_NAME:<string>

Set the Kerberos service name when connecting to Kerberized MongoDB instances. This value must match the service name set on MongoDB instances to which you are connecting.

SERVICE_NAME defaults to mongodb for all clients and MongoDB instances. If you change the saslServiceName setting on a MongoDB instance, you must set SERVICE_NAME to match that setting.

CANONICALIZE_HOST_NAME:true|false
Canonicalize the hostname of the client host machine when connecting to the Kerberos server. This may be required when hosts report different hostnames than what is in the Kerberos database. Defaults to false.
SERVICE_REALM:<string>
Set the Kerberos realm for the MongoDB service. This may be necessary to support cross-realm authentication where the user exists in one realm and the service in another.

Note

The authMechanismProperties option is only supported when authMechanism is GSSAPI.

gssapiServiceName

Set the Kerberos service name when connecting to Kerberized MongoDB instances. This value must match the service name set on MongoDB instances to which you are connecting.

gssapiServiceName defaults to mongodb for all clients and MongoDB instances. If you change saslServiceName setting on a MongoDB instance, you must set gssapiServiceName to match that setting.

gssapiServiceName is a deprecated aliases for authMechanismProperties=SERVICE_NAME:mongodb. For more information on which options your driver supports and their relative priority to each other, reference the documentation for your preferred driver version.

Server Selection and Discovery Options

MongoDB provides the following options to configure how MongoDB drivers and mongos instances select a server to which to direct read or write operations.

Connection Option Description
localThresholdMS

The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. Default: 15 milliseconds.

All drivers use localThresholdMS. Use the localThreshold alias when specifying the latency window size to mongos.

serverSelectionTimeoutMS
Specifies how long (in milliseconds) to block for server selection before throwing an exception. Default: 30,000 milliseconds.
serverSelectionTryOnce

Single-threaded drivers only. When true, instructs the driver to scan the MongoDB deployment exactly once after server selection fails and then either select a server or raise an error. When false, the driver blocks and searches for a server up to the serverSelectionTimeoutMS value. Default: true.

Multi-threaded drivers and mongos do not support serverSelectionTryOnce.

heartbeatFrequencyMS

heartbeatFrequencyMS controls when the driver checks the state of the MongoDB deployment. Specify the interval (in milliseconds) between checks, counted from the end of the previous check until the beginning of the next one.

Default:

  • Single-threaded drivers: 60 seconds.
  • Multi-threaded drivers: 10 seconds.

mongos does not support changing the frequency of the heartbeat checks.

Miscellaneous Configuration

Connection Option Description
appName

Specify a custom app name. The app name appears in

If you do not specify a custom app name, the mongo shell uses the default “MongoDB Shell”.

New in version 4.0.

retryWrites

Enable retryable writes.

Possible values are:

  • true
  • false. The default value for the 3.6 drivers is false.

New in version 3.6.

uuidRepresentation

Possible values are:

standard
The standard binary representation.
csharpLegacy
The default representation for the C# driver.
javaLegacy
The default representation for the Java driver.
pythonLegacy
The default representation for the Python driver.

For the default, see the drivers documentation for your driver.

Note

Not all drivers support the uuidRepresentation option. For information on your driver, see the drivers documentation.

Examples

The following provide example URI strings for common connection targets.

Database Server Running Locally

The following connects to a database server running locally on the default port:

mongodb://localhost

admin Database

The following connects and logs in to the admin database as user sysop with the password moon:

mongodb://sysop:moon@localhost

records Database

The following connects and logs in to the records database as user sysop with the password moon:

mongodb://sysop:moon@localhost/records

UNIX Domain Socket

Use a URL encoded connection string when connecting to a UNIX domain socket.

The following connects to a UNIX domain socket with file path /tmp/mongodb-27017.sock:

mongodb://%2Ftmp%2Fmongodb-27017.sock

Note

Not all drivers support UNIX domain sockets. For information on your driver, see the drivers documentation.

Replica Set with Members on Different Machines

The following connects to a replica set with two members, one on db1.example.net and the other on db2.example.net:

Note

For a replica set, specify the hostname(s) of the mongod instance(s) as listed in the replica set configuration.

mongodb://db1.example.net,db2.example.com/?replicaSet=test

Replica Set with Members on localhost

The following connects to a replica set with three members running on localhost on ports 27017, 27018, and 27019:

Note

For a replica set, specify the hostname(s) of the mongod instance(s) as listed in the replica set configuration.

mongodb://localhost,localhost:27018,localhost:27019/?replicaSet=test

Replica Set with Read Distribution

The following connects to a replica set with three members and distributes reads to the secondaries:

Note

For a replica set, specify the hostname(s) of the mongod instance(s) as listed in the replica set configuration.

mongodb://example1.com,example2.com,example3.com/?replicaSet=test&readPreference=secondary

Replica Set with a High Level of Write Concern

The following connects to a replica set with write concern configured to wait for replication to succeed on at least two members, with a two-second timeout.

Note

For a replica set, specify the hostname(s) of the mongod instance(s) as listed in the replica set configuration.

mongodb://example1.com,example2.com,example3.com/?replicaSet=test&w=2&wtimeoutMS=2000

Sharded Cluster

The following connects to a sharded cluster with three mongos instances:

mongodb://router1.example.com:27017,router2.example2.com:27017,router3.example3.com:27017/