On this page本页内容
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.
You can specify the MongoDB connection string using either:
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:
Note
If the username or password includes the following characters:
those characters must be converted using 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.
Note
If the username or password includes the following characters:
those characters must be converted using percent encoding.
Note
For a connection string to a sharded cluster, specify mongos
hosts in the connection string.
Note
If the username or password includes the following characters:
those characters must be converted using percent encoding.
For more examples, see Examples.
The standard URI connection string includes the following components:
Component | |
---|---|
mongodb:// |
A required prefix to identify that this is a string in the standard connection format. |
username:password@ |
If specified, the client will attempt to authenticate the user to the Note If the username or password includes the following characters: those characters must be converted using percent encoding. See also |
host[:port] |
The host (and optional port number) where the
If the port number is not specified, the default port |
/defaultauthdb |
If both |
?<options> |
If the connection string does not specify a database/ you must specify a slash ( |
New in version 3.6.版本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 seed list, 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 tls
(or the equivalent ssl
) option to true
for the connection. You can override this behavior by explicitly setting the tls
(or the equivalent ssl
) option to false
with tls=false
(or ssl=false
) in the query string.
The following example shows a typical connection string for a DNS seed list connection string:
The corresponding DNS configuration might resemble:
When a client connects to a member of the seed list, the client retrieves a list of replica set members it can connect to. Clients often use DNS aliases in their seed lists which means the host may return a server list that differs from the original seed list. If this happens, clients will use the hostnames provided by the replica set rather than the hostnames listed in the seed list to ensure that replica set members can be reached via the hostnames in the resulting replica set config.
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 seed list connection string supports specifying options as a query string. With a DNS seed list 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:
Taken together, the DNS SRV records and the options specified in the TXT record resolve to the following standard format connection string:
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.
Given the override for the authSource
, the equivalent connection string in the standard format would be:
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 tls
(or the equivalent ssl
) option to true
for the connection. You can override this behavior by explicitly setting the tls
(or the equivalent ssl
) option to false
with tls=false
(or 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 Seed list Connection Format.
This section lists all connection options.
Connection options are pairs in the following form: name=value
.
name
is case insensitive when using a driver.name
is case insensitive when using a version 4.2+
mongo
shell.name
is case sensitive when using a version 4.0 and earlier mongo
shell.value
is always case sensitive.Separate options with the ampersand (i.e. &
) character name1=value1&name2=value2
. In the following example, a connection includes the replicaSet
and connectTimeoutMS
options:
Semi-colon separator for connection string arguments
To provide backwards compatibility, drivers currently accept semi-colons (i.e. ;
) as option separators.
The following connection string to a replica set named myRepl
with members running on the specified hosts:
Connection Option | |
---|---|
|
Specifies the name of the replica set, if the When connecting to a replica set, provide a seed list of the replica set member(s) to the |
The following connection string to a replica set includes tls=true
option (available starting in MongoDB 4.2):
Alternatively, you can also use the equivalent ssl=true
option:
Connection Option | |
---|---|
|
Enables or disables TLS/SSL for the connection:
If the
|
|
A boolean to enable or disables TLS/SSL for the connection:
If the |
|
Specifies the location of a local The client presents this file to the
This option is not supported by all drivers. Refer to the drivers documentation. This connection string option is not available for the
|
|
Specifies the password to de-crypt the This option is not supported by all drivers. Refer to the drivers documentation. This connection string option is not available for the
|
|
Specifies the location of a local This option is not supported by all drivers. Refer to the drivers documentation. This connection string option is not available for the
|
|
Bypasses validation of the certificates presented by the Set to This option is not supported by all drivers. Refer to the drivers documentation. This connection string option is not available for the Warning Disabling certificate validation creates a vulnerability.
|
|
Disables hostname validation of the certificate presented by the Set to This option is not supported by all drivers. Refer to the drivers documentation. This connection string option is not available for the Warning Disabling certificate validation creates a vulnerability.
|
|
Disables various certificate validations. Set to This connection string option is not available for the Warning Disabling certificate validation creates a vulnerability.
|
Connection Option | |
---|---|
|
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. |
|
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. |
Connection Option | |||||||||
---|---|---|---|---|---|---|---|---|---|
|
Comma-delimited string of compressors to enable network compression for communication between this client and a You can specify the following compressors: 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 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 | ||||||||
|
An integer that specifies the compression level if using zlib for You can specify an integer value ranging from
Not supported by the |
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 | |
---|---|
|
The maximum number of connections in the connection pool. The default value is 100 . |
|
The minimum number of connections in the connection pool. The default value is Note The |
|
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. |
|
A number that the driver multiples the This option is not supported by all drivers. |
|
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 describes the level of acknowledgment requested from MongoDB. The write concern option is supported by the:
mongo
shellmongofiles
mongoimport
mongorestore
You can specify the write concern both in the connection string and as a parameter to methods like insert
or update
. If the write concern is specified in both places, the method parameter overrides the connection-string setting.
The following connection string to a replica set specifies "majority"
write concern and a 5 second timeout using the wtimeoutMS
write concern parameter:
Connection Option | |
---|---|
|
Corresponds to the write concern w Option. The You can specify a For details, see w Option. |
|
Corresponds to the write concern wtimeout. When |
|
Corresponds to the write concern j Option option. The If you set If you set |
For more information, see Write Concern.
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
:
Connection Option | |
---|---|
|
The level of isolation. Can accept one of the following values: This connection string option is not available for the |
For more information, see Read Concern.
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.
Note
To specify the hedged reads option using the drivers, refer to the drivers’ read preference API.
For example:例如:
secondary
read preference mode and a maxStalenessSeconds
value of 120 seconds:
secondary
read preference mode and a maxStalenessSeconds
value of 120 seconds:
secondary
read preference mode as well as three readPreferenceTags
:
Order matters when using multiple readPreferenceTags
. The readPreferenceTags
are tried in order until a match is found. Once found, that specification is used to find all eligible matching members and any remaining readPreferenceTags
are ignored. For details, see Order of Tag Matching.
Connection Option | |
---|---|
|
Specifies the read preferences for this connection. Possible values are: Multi-document transactions that contain read operations must use read preference This connection string option is not available for the |
|
Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. For details, see Read Preference 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 Important To use
|
|
Specifies the tags document as a comma-separated list of colon-separated key-value pairs. For example,
To specify a list of tag documents, use multiple Order matters when using multiple This connection string option is not available for the |
For more information, see Read preferences.
The following connection string to a replica set specifies the authSource
to the admin
database. That is, the user credentials are authenticated against the admin
database.
Note
If the username or password includes the following characters:
those characters must be converted using percent encoding.
Connection Option | |
---|---|
|
Specify the database name associated with the user’s credentials. If The MongoDB will ignore |
|
Specify the authentication mechanism that MongoDB will use to authenticate the connection. Possible values include:
MongoDB 4.0 removes support for the Only MongoDB Enterprise To use To use When using Note If the AWS access key ID, secret access key, or session token include the following characters: those characters must be converted using percent encoding. Alternatively, if the AWS access key ID, secret access key, or session token are defined on your platform using their respective AWS IAM environment variables the See Connect to an Atlas Cluster for example usage of the 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. |
|
Specify properties for the specified Possible key-value pairs are:
|
|
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.
|
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 | |
---|---|
|
The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. Default: 15 milliseconds. All drivers use |
|
Specifies how long (in milliseconds) to block for server selection before throwing an exception. Default: 30,000 milliseconds. |
|
Single-threaded drivers only. When Multi-threaded drivers and |
|
Default:
|
Connection Option | |
---|---|
|
Specify a custom app name. The app name appears in
If you do not specify a custom app name, the
|
|
Enables retryable reads. Possible values are:
The
|
|
Enable retryable writes. Possible values are:
MongoDB drivers retry transaction commit and abort operations regardless of the value of
|
|
Possible values are:
For the default, see the drivers documentation for your driver. Note Not all drivers support the |
The following provide example URI strings for common connection targets.
The following connects to a database server running locally on the default port:
admin
Database¶The following connects and logs in to the admin
database as user sysop
with the password moon
:
records
Database¶The following connects and logs in to the records
database as user sysop
with the password moon
:
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
:
Note
Not all drivers support UNIX domain sockets. For information on your driver, see the drivers documentation.
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.
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.
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.
The following connects to a replica set with write concern configured to wait for replication to succeed across a majority of the data-bearing voting 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.
New in version 4.4.版本4.4中的新功能。
The following connects to a MongoDB Atlas cluster which has been configured to support authentication via AWS IAM credentials:
Connecting to Atlas using AWS IAM credentials in this manner uses the MONGODB-AWS
authentication mechanism
and the $external
authSource
, as shown in this example.
If using an AWS session token, as well, provide it with the AWS_SESSION_TOKEN
authMechanismProperties
value, as follows:
Note
If the AWS access key ID, the secret access key, or the session token include the following characters:
those characters must be converted using percent encoding.
You may also set these credentials on your platform using standard AWS IAM environment variables. The mongo
shell checks for the following environment variables when you use the MONGODB-AWS
authentication mechanism
:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
AWS_SESSION_TOKEN
If set, these credentials do not need to be specified in the connection string.
The following example sets these environment variables in the bash
shell:
Syntax for setting environment variables in other shells will be different. Consult the documentation for your platform for more information.
You can verify that these environment variables have been set with the following command:
Once set, the following example connects to a MongoDB Atlas cluster using these environment variables: