Connection String URI Format

This document describes the URI formats for defining connectionsbetween applications and MongoDB instances in the official MongoDBdrivers. For a list of drivers and links todriver 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 connectionURI used to connect to a MongoDB deployment: standalone, replica set,or a sharded cluster.

The standard URI connection scheme has the form:

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

Examples

  • Standalone
  • Replica Set
  • Sharded Cluster
  • For a standalone:
  1. mongodb://mongodb0.example.com:27017/admin
  1. 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 percentencoding.

Note

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

For a replica set, include the replicaSetoption.

  • For a replica set:
  1. mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/admin?replicaSet=myRepl
  1. 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 percentencoding.

Note

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

  • For a sharded cluster:
  1. mongodb://mongos0.example.com:27017,mongos1.example.com:27017,mongos2.example.com:27017/admin
  1. 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 percentencoding.

For more examples, see Examples.

Components

The standard URI connection string includes the following components:

ComponentDescription
mongodb://A required prefix to identify that this is a string in thestandard connection format.
username:password@Optional. Authentication credentials. If specified, the clientwill attempt to log in to the specific database using thesecredentials after connecting.If the username or password includes the at sign @, colon :,slash /, or the percent sign % character, use percentencoding.See also authSource.
host[:port]The host (and optional port number) where themongod instance (or mongosinstance for a sharded cluster) is running. You can specify ahostname, IP address, or UNIX domain socket. Specify as manyhosts as appropriate for your deployment topology:- For a standalone, specify the hostname of the standalonemongod instance.- For a replica set, specify the hostname(s) of the mongodinstance(s) as listed in the replica set configuration.- For a sharded cluster, specify the hostname(s) of themongos instance(s).If the port number is not specified, the default port 27017is used.
/databaseOptional. The name of the database to authenticate if theconnection string includes authentication credentials in theform of username:password@. If /database is notspecified and the connection string includes credentials, thedriver will authenticate to the admin database. See alsoauthSource.
?<options>Optional. A query string that specifies connection specificoptions as <name>=<value> pairs. SeeConnection String Options for a full description ofthese options.If the connection string does not specify a database/ you mustspecify a slash (/) between the last host and thequestion 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 aDNS-constructed seed list. Using DNS toconstruct the available servers list allows more flexibility ofdeployment and the ability to change the servers in rotation withoutreconfiguring clients.

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

Note

Use of the +srv connection string modifierautomatically sets the tls (or the equivalentssl) option to true for the connection. You canoverride this behavior by explicitly setting the tls(or the equivalent ssl) option to false withtls=false (or ssl=false) in the query string.

The following example shows a typical connection string for a DNSseedlist connection string:

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

The corresponding DNS configuration might resemble:

  1. Record TTL Class Priority Weight Port Target
  2. _mongodb._tcp.server.example.com. 86400 IN SRV 0 5 27317 mongodb1.example.com.
  3. _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 parentdomain (in this example, example.com) as the given hostname. Ifthe parent domains and hostname do not match, you will not be able toconnect.

Like the standard connection string, the DNS seedlist connection stringsupports specifying options as a query string. With a DNS seedlistconnection string, you can also specify the following options via aTXT 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 TXTrecord 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:

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

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

  1. 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 optionin the query string. In the following example, the query string has providedan override for the authSource option configured in the TXT recordof the DNS entry above.

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

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

  1. 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 DNSwith records that correspond to the hostname identified in theconnection string. In addition, use of the +srv connection string modifierautomatically sets the tls (or the equivalentssl) option to true for the connection. You canoverride this behavior by explicitly setting the tls(or the equivalent ssl) option to false withtls=false (or ssl=false) in the query string.

See

Connect to a Replica Set Using the DNS Seedlist Connection Format provides an example ofconnecting the mongo shell to a replica set usingthe DNS Seedlist Connection Format.

Connection String Options

This section lists all connection options.

Connection options are pairs in the following form: name=value.

  • The option name is case insensitive when using a driver.
  • The option name is case insensitive when using a version 4.2+mongo shell.
  • The option name is case sensitive when using a version 4.0 andearlier mongo shell.
  • The value is always case sensitive.

Separate options with the ampersand (i.e. &) charactername1=value1&name2=value2. In the following example, aconnection includes the replicaSet andconnectTimeoutMS options:

  1. 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 acceptsemi-colons (i.e. ;) as option separators.

Replica Set Option

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

  1. mongodb://db0.example.com:27017,db1.example.com:27017,db2.example.com:27017/admin?replicaSet=myRepl
Connection OptionDescription
- replicaSet-Specifies the name of the replica set, if themongod is a member of a replica set.When connecting to a replica set, provide a seed list of thereplica set member(s) to the host[:port] component of theuri. For specific details, refer to your driver documentation.

Connection Options

TLS Options

The following connection string to a replica set includestls=true option (available starting in MongoDB 4.2):

  1. mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&tls=true

Alternatively, you can also use the equivalent ssl=true option:

  1. mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&ssl=true
Connection OptionDescription
- tls-Enables or disables TLS/SSL for the connection:- true: Initiate the connection with TLS/SSL. Default forDNS Seedlist Connection Format.- false: Initiate the connection without TLS/SSL. Default forStandard Connection String Format.NoteThe tls option is equivalent to thessl option.If the mongo shell specifies additionaltls/ssl options from thecommand-line, use the —tlscommand-line option instead.New in version 4.2.
- ssl-A boolean to enable or disables TLS/SSL for the connection:- true: Initiate the connection with TLS/SSL. Default forDNS Seedlist Connection Format.- false: Initiate the connection without TLS/SSL. Defaultfor Standard Connection String Format.NoteThe ssl option is equivalent to thetls option.If the mongo shell specifies additionaltls/ssl options from thecommand-line, use the —sslcommand-line option instead.
- tlsCertificateKeyFile-Specifies the location of a local .pem file thatcontains either the client’s TLS/SSL certificate or theclient’s TLS/SSL certificate and key.The client presents this file to themongod/mongos instance.This option is not supported by all drivers. Refer to thedrivers documentation.This connection string option is not available for the mongoshell and the MongoDB utility programs (e.g. mongodump,mongorestore). Use the command-line options instead.New in version 4.2.
- tlsCertificateKeyFilePassword-Specifies the password to de-crypt thetlsCertificateKeyFile.This option is not supported by all drivers. Refer to thedrivers documentation.This connection string option is not available for the mongoshell and the MongoDB utility programs (e.g. mongodump,mongorestore). Use the command-line options instead.New in version 4.2.
- tlsCAFile-Specifies the location of a local .pem file thatcontains the root certificate chain from the CertificateAuthority. This file is used to validate the certificatepresented by the mongod/mongosinstance.This option is not supported by all drivers. Refer to thedrivers documentation.This connection string option is not available for the mongoshell and the MongoDB utility programs (e.g. mongodump,mongorestore). Use the command-line options instead.New in version 4.2.
- tlsAllowInvalidCertificates-Bypasses validation of the certificates presented by themongod/mongos instanceSet to true to connect to MongoDB instances even if theserver’s present invalid certificates.This option is not supported by all drivers. Refer to thedrivers documentation.This connection string option is not available for the mongoshell and the MongoDB utility programs (e.g. mongodump,mongorestore). Use the command-line options instead.WarningDisabling certificate validation creates a vulnerability.New in version 4.2.
- tlsAllowInvalidHostnames-Disables hostname validation of the certificate presented bythe mongod/mongos instance.Set to true to connect to MongoDB instances even if thehostname in the server certificates do not match the server’shost.This option is not supported by all drivers. Refer to thedrivers documentation.This connection string option is not available for the mongoshell and the MongoDB utility programs (e.g. mongodump,mongorestore). Use the command-line options instead.WarningDisabling certificate validation creates a vulnerability.New in version 4.2.
- tlsInsecure-Disables various certificate validations.Set to true to disable certificate validations. The exactvalidatations disabled vary by drivers. Refer to thedrivers documentation.This connection string option is not available for the mongoshell and the MongoDB utility programs (e.g. mongodump,mongorestore). Use the command-line options instead.WarningDisabling certificate validation creates a vulnerability.New in version 4.2.

Timeout Options

Connection OptionDescription
- connectTimeoutMS-The time in milliseconds to attempt a connection before timingout. The default is never to timeout, though different driversmight vary. See the driverdocumentation.
- socketTimeoutMS-The time in milliseconds to attempt a send or receive on asocket before the attempt times out. The default is never totimeout, though different drivers might vary. See thedriver documentation.

Compression Options

Connection OptionDescription
- compressors-Comma-delimited string of compressors to enablenetwork compression for communication between thisclient and a mongod/mongosinstance.You can specify the following compressors:- snappy- zlib (Available in MongoDB 3.6 or greater)- zstd (Available in MongoDB 4.2 or greater)If you specify multiple compressors, then the order in which you listthe compressors matter as well as the communication initiator. Forexample, if the client specifies the following networkcompressors "zlib,snappy" and the mongod specifies"snappy,zlib", messages between the client and themongod uses zlib.ImportantMessages are compressed when both parties enable networkcompression. Otherwise, messages between the parties areuncompressed.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), themongo shell supports the uri connection stringoption compressors.
- zlibCompressionLevel-An integer that specifies the compression level if usingzlib for network compression.You can specify an integer value ranging from -1 to 9:
ValueNotes
-1Default compression level, usually level 6 compression.
0No compression
1 - 9Increasing 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 connectionpools. See your driver documentationfor more information on the connection pooling implementation. Theseoptions allow applications to configure the connection pool whenconnecting to the MongoDB deployment.

Connection OptionDescription
- maxPoolSize-The maximum number of connections in the connection pool. Thedefault value is 100.
- minPoolSize-The minimum number of connections in the connection pool. Thedefault value is 0.NoteThe minPoolSize option is not supported by alldrivers. For information on your driver, see thedrivers documentation.
- maxIdleTimeMS-The maximum number of milliseconds that a connection can remainidle in the pool before being removed and closed.This option is not supported by all drivers.
- waitQueueMultiple-A number that the driver multiples the maxPoolSizevalue to, to provide the maximum number of threads allowed towait for a connection to become available from the pool. Fordefault values, see the /driversdocumentation.This option is not supported by all drivers.
- waitQueueTimeoutMS-The maximum time in milliseconds that a thread can wait for aconnection 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 level ofacknowledgment requested from MongoDB. The write concern option issupported by the:

You can specify the write concern both in the connection string andas a parameter to methods like insert or update. If thewrite concern is specified in both places, the method parameteroverrides the connection-string setting.

The following connection string to a replica set specifies"majority" write concern and a 5 secondtimeout using the wtimeoutMS write concern parameter:

  1. mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&w=majority&wtimeoutMS=5000
Connection OptionDescription
- w-Corresponds to the write concern w Option. The w optionrequests acknowledgement that the write operation has propagatedto a specified number of mongod instances or tomongod instances with specified tags.You can specify a number, thestring majority, or atag 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 timeout. For more information, see wtimeout.
- journal-Corresponds to the write concern j Option option. Thejournal option requests acknowledgement fromMongoDB that the write operation has been written to thejournal. For details, see j Option.If you set journal to true, and specify aw value less than 1, journal prevails.If you set journal to true, and themongod does not have journaling enabled, as withstorage.journal.enabled, then MongoDB will error.

For more information, see Write Concern.

readConcern Options

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

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

The following connection string to a replica set specifiesreadConcernLevel=majority:

  1. mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&readConcernLevel=majority
Connection OptionDescription
- readConcernLevel-The level of isolation. Can accept one of the following values:- local- majority- linearizable- availableThis connection string option is not available for themongo shell. Specify the read concern as anoption to the specific operation.

For more information, see Read Concern.

Read Preference Options

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

For example:

  1. mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&readPreference=secondary&maxStalenessSeconds=120
  • The following connection string to a sharded cluster specifiessecondary read preference mode and amaxStalenessSeconds value of 120 seconds:
  1. mongodb://mongos1.example.com,mongos2.example.com/?readPreference=secondary&maxStalenessSeconds=120
  1. mongodb://mongos1.example.com,mongos2.example.com/?readPreference=secondary&readPreferenceTags=dc:ny,rack:r1&readPreferenceTags=dc:ny&readPreferenceTags=

Order matters when using multiple readPreferenceTags. ThereadPreferenceTags are tried in order until a match is found. Oncefound, that specification is used to find all eligible matchingmembers and any remaining readPreferenceTags are ignored.For details, see Order of Tag Matching.

Connection OptionDescription
- readPreference-Specifies the read preferencesfor this connection. Possible values are:- primary (Default)- primaryPreferred- secondary- secondaryPreferred- nearestMulti-document transactions that containread operations must use read preference primary. Alloperations in a given transaction must route to the same member.This connection string option is not available for themongo shell. See cursor.readPref() andMongo.setReadPref() instead.
- maxStalenessSeconds-Specifies, in seconds, how stale a secondary can be before the clientstops using it for read operations. For details, seemaxStalenessSeconds.By default, there is no maximum staleness and clients will not consider asecondary’s lag when choosing where to direct a read operation.The minimum maxStalenessSeconds value is 90seconds. Specifying a value between 0 and 90 seconds will producean error. MongoDB drivers treat a maxStalenessSeconds valueof -1 as “no max staleness”, the same as ifmaxStalenessSeconds is omitted.ImportantTo use maxStalenessSeconds, all of theMongoDB instances in your deployment must be using MongoDB 3.4 orlater. If any instances are on an earlier version of MongoDB, thedriver or mongod/mongos will raise an error.New in version 3.4.
- readPreferenceTags-Specifies the tags document as a comma-separatedlist of colon-separated key-value pairs. For example,- To specify the tags document { "dc": "ny", "rack": "r1" },use readPreferenceTags=dc:ny,rack:r1 in the connectionstring.- To specify an empty tags document { }, usereadPreferenceTags= without setting the value.To specify a list of tag documents, use multiplereadPreferenceTags. For example,readPreferenceTags=dc:ny,rack:r1&readPreferenceTags=.Order matters when using multiple readPreferenceTags. ThereadPreferenceTags are tried in order until a match isfound. For details, seeOrder of Tag Matching.This connection string option is not available for themongo shell. See cursor.readPref() andMongo.setReadPref() instead.

For more information, see Read preferences.

Authentication Options

The following connection string to a replica set specifies theauthSource to the admin database. That is the usercredentials are authenticated to the admin database.

  1. 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 percentencoding.

Connection OptionDescription
- authSource-Specify the database name associated with the user’scredentials. authSourcedefaults to the database specified in the connection string.For authentication mechanisms that delegate credential storageto other services, the authSource value should be$external as with the PLAIN (LDAP) and GSSAPI(Kerberos) authentication mechanisms.MongoDB will ignore authSource values if theconnection string specifies no username.
- authMechanism-Specify the authentication mechanism that MongoDB will use toauthenticate the connection. Possible values include:- SCRAM-SHA-1- SCRAM-SHA-256 (Added in MongoDB 4.0)- MONGODB-CR (Removed in MongoDB 4.0)- MONGODB-X509- GSSAPI (Kerberos)- PLAIN (LDAP SASL)MongoDB 4.0 removes support for the MONGODB-CRauthentication mechanism. You cannot specify MONGODB-CR asthe authentication mechanism when connecting to MongoDB 4.0+deployments.Only MongoDB Enterprise mongod and mongosinstances provide GSSAPI (Kerberos) and PLAIN (LDAP)mechanisms. To use MONGODB-X509, you must have TLS/SSLEnabled.See Authentication for more information about theauthentication system in MongoDB. Also considerUse x.509 Certificates to Authenticate Clients for moreinformation on x509 authentication.
- authMechanismProperties-Specify properties for the specified authMechanismas 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 KerberizedMongoDB instances. This value must match the service name seton MongoDB instances to which you are connecting.SERVICE_NAME defaults to mongodb for all clients andMongoDB instances. If you change thesaslServiceName setting on a MongoDB instance, youmust set SERVICE_NAME to match that setting.- CANONICALIZE_HOST_NAME:true|false- Canonicalize the hostname of the client host machine whenconnecting to the Kerberos server. This may be required whenhosts report different hostnames than what is in the Kerberosdatabase. Defaults to false.- SERVICE_REALM:<string>- Set the Kerberos realm for the MongoDB service. This may benecessary to support cross-realm authentication where the userexists in one realm and the service in another.NoteThe authMechanismProperties option is onlysupported when authMechanism is GSSAPI.
- gssapiServiceName-Set the Kerberos service name when connecting to KerberizedMongoDB instances. This value must match the service name set onMongoDB instances to which you are connecting.gssapiServiceName defaults to mongodb for allclients and MongoDB instances. If you changesaslServiceName setting on a MongoDB instance, youmust set gssapiServiceName to match that setting.gssapiServiceName is a deprecated aliases forauthMechanismProperties=SERVICE_NAME:mongodb. For more information on whichoptions your driver supports and their relative priority to eachother, reference the documentation for your preferred driverversion.

Server Selection and Discovery Options

MongoDB provides the following options to configure how MongoDB driversand mongos instances select a server to which to direct reador write operations.

Connection OptionDescription
- localThresholdMS-The size (in milliseconds) of the latency window for selectingamong multiple suitable MongoDB instances. Default: 15milliseconds.All drivers use localThresholdMS. Use thelocalThreshold alias when specifying the latency window sizeto mongos.
- serverSelectionTimeoutMS-Specifies how long (in milliseconds) to block for serverselection before throwing an exception. Default: 30,000milliseconds.
- serverSelectionTryOnce-Single-threaded drivers only. When true, instructs thedriver to scan the MongoDB deployment exactly once after serverselection fails and then either select a server or raise anerror. When false, the driver blocks and searches for aserver up to the serverSelectionTimeoutMS value.Default: true.Multi-threaded drivers and mongos do not supportserverSelectionTryOnce.
- heartbeatFrequencyMS-heartbeatFrequencyMS controls when the driverchecks the state of the MongoDB deployment. Specify the interval(in milliseconds) between checks, counted from the end of theprevious 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 ofthe heartbeat checks.

Miscellaneous Configuration

Connection OptionDescription
- appName-Specify a custom app name. The app name appears in- mongod and mongoslogs,- the currentOp.appName field in the currentOpcommand and db.currentOp() method output,- the system.profile.appName field in the databaseprofiler output.If you do not specify a custom app name, the mongoshell uses the default “MongoDB Shell”.New in version 4.0.
- retryWrites-Enable retryable writes.Possible values are:-true. Enables retryable writes for the connection.Official MongoDB 4.2-compatible drivers default to true.-false. Disables retryable writes for the connection.Official MongoDB 4.0 and 3.6-compatible drivers default to false.MongoDB drivers retrytransaction commit and abort operationsregardless of the value of retryWrites. For moreinformation on transaction retryability, seeTransaction Error Handling.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 driversdocumentation for your driver.NoteNot all drivers support the uuidRepresentationoption. 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 thedefault port:

  1. mongodb://localhost

admin Database

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

  1. mongodb://sysop:moon@localhost

records Database

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

  1. mongodb://sysop:moon@localhost/records

UNIX Domain Socket

Use a URL encoded connection string when connecting to a UNIX domainsocket.

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

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

Note

Not all drivers support UNIX domain sockets. For informationon your driver, see the driversdocumentation.

Replica Set with Members on Different Machines

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

Note

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

  1. 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 onports 27017, 27018, and 27019:

Note

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

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

Replica Set with Read Distribution

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

Note

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

  1. 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 waitfor replication to succeed across a majority of the data-bearing votingmembers, with a two-second timeout.

Note

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

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

Sharded Cluster

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

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