On this page本页内容
This document describes the URI formats for defining connections between applications and MongoDB instances in the official MongoDB Drivers. 本文档描述了在官方MongoDB驱动程序中定义应用程序和MongoDB实例之间连接的URI格式。For a list of drivers and links to driver documentation, see Drivers.有关驱动程序列表和驱动程序文档链接,请参阅驱动程序。
You can specify the MongoDB connection string using either:可以使用以下任一方法指定MongoDB连接字符串:
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.本节介绍用于连接MongoDB部署的MongoDB连接URI的标准格式:独立、副本集或分片集群。
The standard URI connection scheme has the form:标准URI连接方案的形式如下:
mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
For a standalone:对于单机版:
mongodb://mongodb0.example.com:27017
For a standalone that enforces access control:对于强制访问控制的单机版:
mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017/?authSource=admin
If the username or password includes the following characters:如果用户名或密码包含以下字符:
: / ? # [ ] @
those characters must be converted using percent encoding.这些字符必须使用百分比编码进行转换。
For a replica set, specify the hostname(s) of the 对于副本集,请指定副本集配置中列出的mongod
instance(s) as listed in the replica set configuration.mongod
实例的主机名。
For a replica set, include the 对于副本集,请包括replicaSet
option.replicaSet
选项。
For a replica set:对于副本集:
mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/?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/?authSource=admin&replicaSet=myRepl
If the username or password includes the following characters:如果用户名或密码包含以下字符:
: / ? # [ ] @
those characters must be converted using percent encoding.这些字符必须使用百分比编码进行转换。
For a connection string to a sharded cluster, specify 对于到分片集群的连接字符串,请在连接字符串中指定mongos
hosts in the connection string.mongos
主机。
For a sharded cluster:对于分片群集:
mongodb://mongos0.example.com:27017,mongos1.example.com:27017,mongos2.example.com:27017
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/?authSource=admin
If the username or password includes the following characters:如果用户名或密码包含以下字符:
: / ? # [ ] @
those characters must be converted using percent encoding.这些字符必须使用百分比编码进行转换。
MongoDB Atlas provides the connection strings for your deployment when you click the Connect button in the Atlas UI. 当您在Atlas UI中单击“连接”按钮时,MongoDB Atlas会为您的部署提供连接字符串。To register a new Atlas account, start at the MongoDB Atlas registration page. 要注册新的Atlas帐户,请从MongoDB Atlas注册页面开始。To learn more, see Get Started with Atlas.要了解更多信息,请参阅Atlas入门。
Your Atlas connection string might resemble the following example:Atlas连接字符串可能类似于以下示例:
mongosh "mongodb+srv://cluster0.example.mongodb.net myFirstDatabase" --username JohnDoe
The standard URI connection string includes the following components:标准URI连接字符串包括以下组件:
mongodb:// | |
username:password@ |
: / ? # [ ] @
|
host[:port] |
|
/defaultauthdb |
|
?<options> |
|
In addition to the standard connection format, MongoDB supports a DNS-constructed seed list. 除了标准连接格式外,MongoDB还支持DNS构造的种子列表。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.使用DNS构建可用服务器列表,可以更灵活地部署服务器,并且能够在不重新配置客户端的情况下轮流更改服务器。
In order to leverage the DNS seed list, use a connection string prefix of 为了利用DNS种子列表,请使用连接字符串前缀mongodb+srv
rather than the standard mongodb
. mongodb+srv
,而不是标准的mongodb
。The +srv
indicates to the client that the hostname that follows corresponds to a DNS SRV record. +srv
向客户端指示,后面的主机名对应于DNS srv记录。The driver or 然后,驱动程序或mongosh
will then query the DNS for the record to determine which hosts are running the mongod
instances.mongosh
将查询DNS中的记录,以确定哪些主机正在运行mongod
实例。
Use of the 使用+srv
connection string modifier automatically sets the tls
(or the equivalent ssl
) option to true
for the connection. +srv
连接字符串修饰符会自动将连接的tls
(或等效的ssl
)选项设置为true
。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.tls=false
(或ssl=false
)将tls
(或等效的ssl
)选项显式设置为false
,可以覆盖此行为。
The following example shows a typical connection string for a DNS seed list connection string:以下示例显示了DNS种子列表连接字符串的典型连接字符串:
mongodb+srv://server.example.com/
The corresponding DNS configuration might resemble:相应的DNS配置可能类似于:
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.
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. 客户端通常在其种子列表中使用DNS别名,这意味着主机可能返回与原始种子列表不同的服务器列表。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.如果发生这种情况,客户端将使用复制集提供的主机名,而不是种子列表中列出的主机名,以确保可以通过生成的复制集配置中的主机名访问复制集成员。
The hostnames returned in SRV records must share the same parent domain (in this example, SRV记录中返回的主机名必须与给定主机名共享同一父域(在本例中为example.com
) as the given hostname. example.com
)。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. 与标准连接字符串一样,DNS种子列表连接字符串支持将选项指定为查询字符串。With a DNS seed list connection string, you can also specify the following options via a TXT record:使用DNS种子列表连接字符串,还可以通过TXT记录指定以下选项:
replicaSet
authSource
You may only specify one TXT record per 每个mongod
instance. mongod
实例只能指定一条TXT记录。If multiple TXT records appear in the DNS and/or if the TXT record contains an option other than 如果DNS中出现多个TXT记录和/或TXT记录包含replicaSet
or authSource
, the client will return an error.replicaSet
或authSource
以外的选项,则客户端将返回错误。
The TXT record for the server.example.com
DNS entry would resemble:server.example.com
DNS条目的TXT记录类似于:
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:总之,DNS SRV记录和TXT记录中指定的选项解析为以下标准格式的连接字符串:
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. 通过在查询字符串中传递选项,可以覆盖TXT记录中指定的选项。In the following example, the query string has provided an override for the 在下面的示例中,查询字符串为上面DNS条目的TXT记录中配置的authSource
option configured in the TXT record of the DNS entry above.authSource
选项提供了覆盖。
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:authSource
的覆盖,标准格式中的等效连接字符串为:
mongodb://mongodb1.example.com:27317,mongodb2.example.com:27017/?connectTimeoutMS=300000&replicaSet=mySet&authSource=aDifferentAuthDB
The 如果没有与连接字符串中标识的主机名对应的记录可用的DNS,mongodb+srv
option will fail if there is no available DNS with records that correspond to the hostname identified in the connection string. mongodb+srv
选项将失败。In addition, use of the 此外,使用+srv
connection string modifier automatically sets the tls
(or the equivalent ssl
) option to true
for the connection. +srv
连接字符串修饰符会自动将连接的tls
(或等效的ssl
)选项设置为true
。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.tls=false
(或ssl=false
)将tls
(或等效的ssl
)选项显式设置为false
,可以覆盖此行为。
Connect to a Replica Set Using the DNS Seedlist Connection Format使用DNS种子列表连接格式连接到副本集 provides an example of connecting 提供了使用DNS种子列表连接格式将mongosh
to a replica set using the DNS Seed list Connection Format.mongosh
连接到副本集的示例。
This section lists all connection options.本节列出了所有连接选项。
Connection options are pairs in the following form: 连接选项是以下形式的配对:name=value
.name=value
。
name
is case insensitive when using a driver.name
不区分大小写。name
is case insensitive when using mongosh
, or the version 4.2 or later legacy mongo
shell.mongosh
或4.2或更高版本的传统mongo shell时,选项名称不区分大小写。name
is case sensitive when using a version 4.0 and earlier legacy mongo
shell.mongo
shell时,选项name
区分大小写。value
is always case sensitive.value
始终区分大小写。Separate options with the ampersand (i.e. 分隔选项用符号ampersand(即&
) character name1=value1&name2=value2
. &
)字符name1=value1&name2=value2
。In the following example, a connection includes the 在以下示例中,连接包括replicaSet
and connectTimeoutMS
options:replicaSet
和connectTimeoutMS
选项:
mongodb://db1.example.net:27017,db2.example.net:2500/?replicaSet=test&connectTimeoutMS=300000
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:myRepl
的副本集,其中的成员在指定的主机上运行:
mongodb://db0.example.com:27017,db1.example.com:27017,db2.example.com:27017/?replicaSet=myRepl
replicaSet |
|
The following connection string to a replica set includes 副本集的以下连接字符串包括tls=true
option (available starting in MongoDB 4.2):tls=true
选项(从MongoDB 4.2开始提供):
mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&tls=true
Alternatively, you can also use the equivalent 或者,您也可以使用等效的ssl=true
option:ssl=true
选项:
mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&ssl=true
tls |
|
ssl |
|
tlsCertificateKeyFile |
mongod / mongos 30 days of the mongod/mongos host system time. mongod /mongos 主机系统时间的30 天内过期,则会在连接时记录警告。
|
tlsCertificateKeyFilePassword |
|
tlsCAFile |
|
tlsAllowInvalidCertificates |
|
tlsAllowInvalidHostnames |
|
tlsInsecure |
|
connectTimeoutMS | |
socketTimeoutMS |
compressors |
| ||||||||
zlibCompressionLevel |
|
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.这些选项允许应用程序在连接到MongoDB部署时配置连接池。
maxPoolSize | 100 .100 。 |
minPoolSize |
|
maxIdleTimeMS |
|
waitQueueMultiple |
|
waitQueueTimeoutMS |
|
Write concern写关注 describes the level of acknowledgment requested from MongoDB. 描述从MongoDB请求的确认级别。The write concern option is supported by the:写关注点选项受以下选项支持:
mongosh
mongofiles
mongoimport
mongorestore
You can specify the write concern both in the connection string and as a parameter to methods like 您可以在连接字符串中指定写关注点,并将其作为insert
or update
. insert
或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:wtimeoutMS
写入关注参数指定"majority"
写入问题和5秒超时:
mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&w=majority&wtimeoutMS=5000
w |
|
wtimeoutMS |
|
journal |
|
For more information, see Write Concern.有关更多信息,请参阅写关注。
readConcern
OptionsFor the WiredTiger storage engine, MongoDB 3.2 introduces the readConcern option for replica sets and replica set shards.对于WiredTiger存储引擎,MongoDB 3.2为副本集和副本集分片引入了readConcern选项。
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
:readConcernLevel=majority
:
mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&readConcernLevel=majority
readConcernLevel |
|
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.这些参数允许您在连接字符串中指定每个连接的读取首选项。
To specify the hedged reads option using the drivers, refer to the drivers' read preference API.要使用驱动程序指定模糊读取选项,请参阅驱动程序的读取首选项API。
For example:例如:
The following connection string to a replica set specifies 副本集的以下连接字符串指定secondary
read preference mode and a maxStalenessSeconds
value of 120 seconds:secondary
读取首选项模式和120秒的maxStalenessSeconds
值:
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:secondary
读取首选项模式和120秒的maxStalenessSeconds
值:
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 three readPreferenceTags
:secondary
读取首选项模式以及三个readPreferenceTags
:
mongodb://mongos1.example.com,mongos2.example.com/?readPreference=secondary&readPreferenceTags=dc:ny,rack:r1&readPreferenceTags=dc:ny&readPreferenceTags=
Order matters when using multiple 使用多个readPreferenceTags
. readPreferenceTags
时,顺序很重要。The readPreferenceTags
are tried in order until a match is found. readPreferenceTags
会按顺序尝试,直到找到匹配项。Once found, that specification is used to find all eligible matching members and any remaining 一旦找到,该规范将用于查找所有符合条件的匹配成员,并忽略任何剩余的readPreferenceTags
are ignored. readPreferenceTags
。For details, see Order of Tag Matching.有关详细信息,请参阅标记匹配的顺序。
readPreference |
|
maxStalenessSeconds |
|
readPreferenceTags |
|
For more information, see Read preferences.有关更多信息,请参阅读取首选项。
The following connection string to a replica set specifies the 以下副本集的连接字符串指定了authSource
to the admin
database. admin
数据库的authSource
。That is, the user credentials are authenticated against the 也就是说,用户凭据根据admin
database.admin
数据库进行身份验证。
mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/?replicaSet=myRepl&authSource=admin
If the username or password includes the following characters:如果用户名或密码包含以下字符:
: / ? # [ ] @
those characters must be converted using percent encoding.这些字符必须使用百分比编码进行转换。
authSource |
|
authMechanism |
: / ? # [ ] @
|
authMechanismProperties |
|
gssapiServiceName |
|
MongoDB provides the following options to configure how MongoDB drivers and MongoDB提供以下选项来配置MongoDB驱动程序和mongos
instances select a server to which to direct read or write operations.mongos
实例如何选择要将读写操作定向到的服务器。
localThresholdMS |
|
serverSelectionTimeoutMS | |
serverSelectionTryOnce |
|
heartbeatFrequencyMS |
Default:
|
appName |
|
retryReads |
|
retryWrites | Enable retryable writes.
|
uuidRepresentation |
|
The following provide example URI strings for common connection targets.下面提供了常见连接目标的URI字符串示例。
The following connects to a database server running locally on the default port:以下连接到在默认端口上本地运行的数据库服务器:
mongodb://localhost
admin
The following connects and logs in to the 以下内容以用户admin
database as user sysop
with the password moon
:sysop
的身份连接并登录到admin
数据库,密码为moon
:
mongodb://sysop:moon@localhost
records
The following connects and logs in to the 以下内容以用户records
database as user sysop
with the password moon
:sysop
的身份连接并登录到records
数据库,密码为moon
:
mongodb://sysop:moon@localhost/records
Use a URL encoded connection string when connecting to a UNIX domain socket.连接到UNIX域套接字时,请使用URL编码的连接字符串。
The following connects to a UNIX domain socket with file path 以下连接到文件路径为/tmp/mongodb-27017.sock
:/tmp/mongodb-27017.sock
的UNIX域套接字:
mongodb://%2Ftmp%2Fmongodb-27017.sock
The following connects to a replica set with two members, one on 以下内容连接到具有两个成员的副本集,一个在db1.example.net
and the other on db2.example.net
:db1.example.net
上,另一个在db2.example.net
上:
For a replica set, specify the hostname(s) of the 对于副本集,请指定副本集配置中列出的mongod
instance(s) as listed in the replica set configuration.mongod
实例的主机名。
mongodb://db1.example.net,db2.example.com/?replicaSet=test
localhost
localhost
上有成员的副本集The following connects to a replica set with three members running on 以下连接到一个副本集,其中三个成员在端口localhost
on ports 27017
, 27018
, and 27019
:27017
、27018
和27019
的本地主机上运行:
For a replica set, specify the hostname(s) of the 对于副本集,请指定副本集配置中列出的mongod
instance(s) as listed in the replica set configuration.mongod
实例的主机名。
mongodb://localhost,localhost:27018,localhost:27019/?replicaSet=test
The following connects to a replica set with three members and distributes reads to the secondaries:以下内容连接到一个包含三个成员的副本集,并将读取内容分发到二级副本:
For a replica set, specify the hostname(s) of the 对于副本集,请指定副本集配置中列出的mongod
instance(s) as listed in the replica set configuration.mongod
实例的主机名。
mongodb://example1.com,example2.com,example3.com/?replicaSet=test&readPreference=secondary
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.下面连接到一个副本集,该副本集的写入问题被配置为等待复制在大多数数据承载投票成员之间成功,并有两秒钟的超时。
For a replica set, specify the hostname(s) of the 对于副本集,请指定副本集配置中列出的mongod
instance(s) as listed in the replica set configuration.mongod
实例的主机名。
mongodb://example1.com,example2.com,example3.com/?replicaSet=test&w=majority&wtimeoutMS=2000
The following connects to a sharded cluster with three 以下连接到具有三个mongos
instances:mongos
实例的分片集群:
mongodb://router1.example.com:27017,router2.example2.com:27017,router3.example3.com:27017/
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:以下连接到MongoDB Atlas群集,该群集已配置为支持通过AWS IAM凭据进行身份验证:
mongosh 'mongodb+srv://<aws access key id>:<aws secret access key>@cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS'
Connecting to Atlas using AWS IAM credentials in this manner uses the 以这种方式使用AWS IAM凭据连接到Atlas使用MONGODB-AWS
authentication mechanism
and the $external
authSource
, as shown in this example.MONGODB-AWS
身份验证机制和$external
authSource
,如本例所示。
If using an AWS session token, as well, provide it with the 如果同时使用AWS会话令牌,请为其提供AWS_SESSION_TOKEN
authMechanismProperties
value, as follows:AWS_SESSION_TOKEN
authMechanismProperties
值,如下所示:
mongosh 'mongodb+srv://<aws access key id>:<aws secret access key>@cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:<aws session token>'
If the AWS access key ID, the secret access key, or the session token include the following characters:如果AWS访问密钥ID、秘密访问密钥或会话令牌包含以下字符:
: / ? # [ ] @
those characters must be converted using percent encoding.这些字符必须使用百分比编码进行转换。
You may also set these credentials on your platform using standard AWS IAM environment variables. 您还可以使用标准AWS IAM环境变量在平台上设置这些凭据。使用mongosh
checks for the following environment variables when you use the MONGODB-AWS
authentication mechanism
:MONGODB-AWS
身份验证机制时,mongosh
会检查以下环境变量:
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:bash
shell中设置这些环境变量:
export AWS_ACCESS_KEY_ID='<aws access key id>' export AWS_SECRET_ACCESS_KEY='<aws secret access key>' export AWS_SESSION_TOKEN='<aws session token>'
Syntax for setting environment variables in other shells will be different. 在其他shell中设置环境变量的语法将有所不同。Consult the documentation for your platform for more information.有关更多信息,请参阅平台的文档。
You can verify that these environment variables have been set with the following command:您可以使用以下命令验证这些环境变量是否已设置:
env | grep AWS
Once set, the following example connects to a MongoDB Atlas cluster using these environment variables:设置后,以下示例使用以下环境变量连接到MongoDB Atlas集群:
mongosh 'mongodb+srv://cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS'