Docs HomeMongoDB Manual5.3

Connection String URI Format连接字符串URI格式

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.有关驱动程序列表和驱动程序文档链接,请参阅驱动程序

Connection String Formats连接字符串格式

You can specify the MongoDB connection string by using either:您可以使用以下任一项指定MongoDB连接字符串:

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.本节描述了用于连接到MongoDB部署的MongoDB连接URI的标准格式:独立、副本集或分片集群。

The standard URI connection scheme has the form:标准URI连接方案的形式如下:

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

Examples实例

  • 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
    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.对于副本集,指定副本集配置中列出的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
    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.对于到分片集群的连接字符串,请在连接字符串中指定mongos-hosts。

  • 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
    Note

    If the username or password includes the following characters:如果用户名或密码包含以下字符:

    $ : / ? # [ ] @

    those characters must be converted using percent encoding.这些字符必须使用百分比编码进行转换。

To connect to your deployment in MongoDB Atlas, use the SRV connection string provided in the Atlas UI when you click the Connect button. 要连接到MongoDB Atlas中的部署,请在单击“连接”按钮时使用Atlas UI中提供的SRV连接字符串。To learn more, see SRV Connection Format.要了解更多信息,请参阅SRV连接格式

Your Atlas connection string might resemble the following example:Atlas连接字符串可能类似于以下示例:

mongosh "mongodb+srv://cluster0.example.mongodb.net myFirstDatabase" --username JohnDoe

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入门

For more examples, see Examples.有关更多示例,请参阅示例

Components组件

The standard URI connection string includes the following components:标准URI连接字符串包括以下组件:

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 authenticate the user to the authSource. 如果指定,客户端将尝试向authSource验证用户。If authSource is unspecified, the client will attempt to authenticate the user to the defaultauthdb. 如果未指定authSource,则客户端将尝试向defaultauthdb验证用户。And if the defaultauthdb is unspecified, to the admin database. 如果未指定defaultauthdb,则返回到admin数据库。
Note
If the username or password includes the following characters:如果用户名或密码包含以下字符:
$ : / ? # [ ] @
those characters must be converted using percent encoding.这些字符必须使用百分比编码进行转换。
See also authSource. 另请参阅authSource
host[:port]The host (and optional port number) where the mongod instance (or mongos instance for a sharded cluster) is running. mongod实例(或分片集群的mongos实例)运行的主机(和可选端口号)。You can specify a hostname, IP address, or UNIX domain socket. 您可以指定主机名、IP地址或UNIX域套接字。Specify as many hosts as appropriate for your deployment topology:根据部署拓扑指定尽可能多的主机:
  • For a standalone, specify the hostname of the standalone mongod instance.对于单机版,请指定单机版mongod实例的主机名。
  • For a replica set, specify the hostname(s) of the mongod instance(s) as listed in the replica set configuration.对于副本集,指定副本集配置中列出的mongod实例的主机名。
  • For a sharded cluster, specify the hostname(s) of the mongos instance(s).对于分片集群,指定mongos实例的主机名。
If the port number is not specified, the default port 27017 is used. 如果未指定端口号,则使用默认端口27017
/defaultauthdbOptional.可选的。The authentication database to use if the connection string includes username:password@ authentication credentials but the authSource option is unspecified.如果连接字符串包括username:password@身份验证凭据,但authSource选项未指定,则要使用的身份验证数据库。
If both authSource and defaultauthdb are unspecified, the client will attempt to authenticate the specified user to the admin database. 如果未指定authSourcedefaultauthdb,则客户端将尝试向admin数据库验证指定的用户。
?<options>Optional.可选的。A query string that specifies connection specific options as <name>=<value> pairs. 将特定于连接的选项指定为<name>=<value>对的查询字符串。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. 如果连接字符串没有指定数据库/,则必须在最后一个主机和选项字符串开头的问号(?)之间指定一个斜线(/)。

SRV Connection FormatSRV连接格式

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 mongodb+srv rather than the standard mongodb. 为了利用DNS种子列表,请使用mongodb+srv的连接字符串前缀,而不是标准的mongodbThe +srv indicates to the client that the hostname that follows corresponds to a DNS SRV record. The driver or mongosh will then query the DNS for the record to determine which hosts are running the mongod or mongos instances.+srv向客户端指示后面的主机名对应于DNS srv记录。然后,驱动程序或mongosh将查询DNS中的记录,以确定哪些主机正在运行mongodmongos实例。

Note

Use of the +srv connection string modifier automatically sets the tls (or the equivalent ssl) option to true for the connection. 使用+srv连接字符串修饰符会自动将连接的tls(或等效的ssl)选项设置为trueYou 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(或等效的ssl)选项设置为false,并使用tls=false(或ssl=false)来覆盖此行为。

When using the +srv format, you must specify the hostname, domain, and top-level domain (TLD) in the following format:使用+srv格式时,必须按以下格式指定hostnamedomain顶级域(TLD) <hostname>.<domain>.<TLD>. This table shows how the placeholders correspond to example values:此表显示占位符如何与示例值相对应:

Placeholder占位符Example实例
<hostname>server
<domain>example
<TLD>com
<hostname>.<domain>.<TLD>server.example.com

This example shows a DNS seed list connection string that correctly uses the <hostname>.<domain>.<TLD> format.此示例显示正确使用<hostname>.<domain>.<TLD>格式的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.

Individual SRV records must be in _mongodb._tcp.<hostname>.<domain>.<TLD> format.单个SRV记录必须位于_mongodb._tcp.<hostname>.<domain>.<TLD>格式。

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.如果发生这种情况,客户端将使用副本集提供的主机名,而不是种子列表中列出的主机名来确保可以通过生成的副本集配置中的主机名访问副本集成员。

Important

The hostnames returned in SRV records must share the same parent domain (in this example, example.com) as the given hostname. SRV记录中返回的主机名必须与给定主机名共享相同的父域(在本例中为example.com)。If the parent domains and hostname do not match, you will not be able to connect.如果父域和主机名不匹配,您将无法连接。

This example shows a DNS seed list connection string that is missing the <hostname>. 此示例显示缺少<hostname>的DNS种子列表连接字符串。This is incorrect and raises an error.这是不正确的,并引发错误。

# This connection string is missing the <hostname> and raises a connection error

mongodb+srv://example.com/

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 replicaSet or authSource, the client will return an error.如果DNS中出现多个TXT记录和/或TXT记录包含replicaSetauthSource以外的选项,则客户端将返回错误。

The TXT record for the server.example.com DNS entry would resemble:server.example.comDNS条目的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 authSource option configured in the TXT record of the DNS entry above.在以下示例中,查询字符串为上面DNS条目的TXT记录中配置的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
Note

The mongodb+srv option fails if there is no available DNS with records that correspond to the hostname identified in the connection string. 如果没有与连接字符串中标识的主机名对应的记录的可用DNS,则mongodb+srv选项将失败。If you use the +srv connection string modifier, the tls (or the equivalent ssl) option is set to true for the connection. 如果使用+srv连接字符串修饰符,则连接的tls(或等效的ssl)选项将设置为trueYou 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(或等效的ssl)选项设置为false,并使用tls=false(或ssl=false)来覆盖此行为。

For an example that connects mongosh to a replica set using the DNS seed list connection format, see mongosh Connection Options.有关使用DNS种子列表连接格式将mongosh连接到副本集的示例,请参阅mongosh连接选项

Connection String Options连接字符串选项

This section lists all connection options.本节列出了所有连接选项。

Connection options are pairs in the following form: name=value.连接选项是以下形式的对:name=value

  • The option name is case insensitive when using a driver.使用驱动程序时,选项name不区分大小写。
  • The option name is case insensitive when using mongosh.使用mongosh时,选项name不区分大小写。
  • The value is always case sensitive.value始终区分大小写。

Separate options with the ampersand (i.e. &) character name1=value1&name2=value2. 用与号(即&)字符分隔选项name1=value1&name2=value2In the following example, a connection includes the replicaSet and connectTimeoutMS options:在以下示例中,连接包括replicaSetconnectTimeoutMS选项:

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

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:以下连接字符串指向名为myRepl的复制副本集,该复制副本集的成员在指定的主机上运行:

mongodb://db0.example.com:27017,db1.example.com:27017,db2.example.com:27017/?replicaSet=myRepl
Connection Option连接选项Description描述
replicaSet Specifies the name of the replica set, if the mongod is a member of a replica set. Set the replicaSet connection option to ensure consistent behavior across drivers.如果mongod副本集的成员,则指定副本集的名称。设置replicaSet连接选项以确保驱动程序之间的行为一致。
When connecting to a replica set, provide a seed list of the replica set member(s) to the host[:port] component of the uri. 连接到副本集时,请向uri的host[:port]组件提供副本集成员的种子列表For specific details, refer to your driver documentation. 有关具体细节,请参阅您的驱动程序文档。

Connection Options连接选项

TLS OptionsTLS选项

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
Connection Option连接选项Description描述
tls Enables or disables TLS/SSL for the connection:为连接启用或禁用TLS/SSL:
Note
The tls option is equivalent to the ssl option. tls选项相当于ssl选项。
If the mongosh shell specifies additional tls/ssl options from the command-line, use the --tls command-line option instead. 如果mongosh shell从命令行指定了额外的tls/ssl选项,请改用--tls命令行选项。
New in version 4.2. 4.2版新增。
ssl A boolean to enable or disables TLS/SSL for the connection:用于为连接启用或禁用TLS/SSL的布尔值:
Note
The ssl option is equivalent to the tls option. ssl选项相当于tls选项。
If the mongosh shell specifies additional tls/ssl options from the command-line, use the --ssl command-line option instead. 如果mongosh shell从命令行指定了额外的tls/ssl选项,请改用--ssl命令行选项。
tlsCertificateKeyFile Specifies the location of a local .pem file that contains either the client's TLS/SSL X.509 certificate or the client's TLS/SSL certificate and key.指定本地.pem文件的位置,该文件包含客户端的TLS/SSL X.509证书或客户端的TLS/ASL证书和键。
The client presents this file to the mongod / mongos instance. 客户端将此文件呈现给mongod/mongos实例。
Changed in version 4.44.4版更改: mongod / mongos logs a warning on connection if the presented x.509 certificate expires within 30 days of the mongod/mongos host system time. 如果提供的x.509证书在mongod/mongos主机系统时间后30天内过期,则在连接时记录警告。See x.509 Certificates Nearing Expiry Trigger Warnings for more information. 有关详细信息,请参阅x.509证书接近到期触发警告This option is not supported by all drivers. 并非所有驱动程序都支持此选项。Refer to the Drivers documentation.请参阅驱动程序文档。
This connection string option is not available for the mongo shell. 此连接字符串选项不适用于mongo shell。Use the command-line option instead. 请改用命令行选项。
New in version 4.2. 4.2版新增。
tlsCertificateKeyFilePassword Specifies the password to de-crypt the tlsCertificateKeyFile.指定对tlsCertificateKeyFile进行解密的密码。
This option is not supported by all drivers. 并非所有驱动程序都支持此选项。Refer to the Drivers documentation.请参阅驱动程序文档。
This connection string option is not available for the mongo shell. 此连接字符串选项不适用于mongo shell。Use the command-line option instead. 请改用命令行选项。
New in version 4.2. 4.2版新增。
tlsCAFile Specifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority. 指定本地.pem文件的位置,该文件包含来自证书颁发机构的根证书链。This file is used to validate the certificate presented by the mongod / mongos instance.此文件用于验证mongod/mongos实例提供的证书。
This option is not supported by all drivers. 并非所有驱动程序都支持此选项。Refer to the Drivers documentation.请参阅驱动程序文档。
This connection string option is not available for the mongo shell. 此连接字符串选项不适用于mongo shell。Use the command-line option instead. 请改用命令行选项。
New in version 4.2. 4.2版新增。
tlsAllowInvalidCertificates Bypasses validation of the certificates presented by the mongod / mongos instance绕过mongod/mongos实例提供的证书验证
Set to true to connect to MongoDB instances even if the server's present invalid certificates.设置为true可连接到MongoDB实例,即使服务器提供的证书无效。
This option is not supported by all drivers. Refer to the Drivers documentation.并非所有驱动程序都支持此选项。请参阅驱动程序文档。
This connection string option is not available for the mongo shell. 此连接字符串选项不适用于mongo shell。Use the command-line option instead. 请改用命令行选项。
Warning
Disabling certificate validation creates a vulnerability. 禁用证书验证会产生漏洞。
New in version 4.2. 4.2版新增。
tlsAllowInvalidHostnames Disables hostname validation of the certificate presented by the mongod / mongos instance.禁用mongod/mongos实例提供的证书的主机名验证。
Set to true to connect to MongoDB instances even if the hostname in the server certificates do not match the server's host.设置为true可连接到MongoDB实例,即使服务器证书中的主机名与服务器的主机不匹配。
This option is not supported by all drivers. Refer to the Drivers documentation.并非所有驱动程序都支持此选项。请参阅驱动程序文档。
This connection string option is not available for the mongo shell. 此连接字符串选项不适用于mongo shell。Use the command-line option instead. 请改用命令行选项。
Warning
Disabling certificate validation creates a vulnerability. 禁用证书验证会产生漏洞。
New in version 4.2. 4.2版新增。
tlsInsecure Disables various certificate validations.禁用各种证书验证。
Set to true to disable certificate validations. 设置为true可禁用证书验证。The exact validatations disabled vary by drivers. Refer to the Drivers documentation.禁用的确切验证因驱动程序而异。请参阅驱动程序文档。
This connection string option is not available for the mongo shell. 此连接字符串选项不适用于mongo shell。Use the command-line option instead. 请改用命令行选项。
Warning
Disabling certificate validation creates a vulnerability. 禁用证书验证会产生漏洞。
New in version 4.2. 4.2版新增。

Timeout Options超时选项

Connection Option连接选项Description描述
connectTimeoutMS The time in milliseconds to attempt a connection before timing out. 超时前尝试连接的时间(以毫秒为单位)。The default is 10,000 milliseconds, but specific drivers might have a different default. 默认值为10000毫秒,但特定的驱动程序可能有不同的默认值。For details, 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.请参阅驱动程序文档。

Compression Options压缩选项

Connection Option连接选项Description描述
compressors Comma-delimited string of compressors to enable network compression for communication between this client and a mongod / mongos instance.以逗号分隔的压缩器字符串,用于启用此客户端和mongod/mongos实例之间通信的网络压缩。
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 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. 例如,如果客户端指定以下网络压缩器"zlib,snappy",而mongod指定"snappy,zlib",则客户端和mongod之间的消息将使用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. 如果双方不共享至少一个公共压缩器,则双方之间的消息将被解压缩。
mongosh supports the uri connection string option compressors. mongosh支持uri连接字符串选项compressors
zlibCompressionLevel An integer that specifies the compression level if using zlib for network compression.如果使用zlib进行网络压缩,则指定压缩级别的整数。
You can specify an integer value ranging from -1 to 9:您可以指定范围从-19的整数值:
ValueNotes备注
-1Default compression level, usually level 6 compression.默认压缩级别,通常为6级压缩。
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.提供了最好的压缩但速度最慢。

Supported by mongosh.mongosh支持。

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.这些选项允许应用程序在连接到MongoDB部署时配置连接池。

Connection Option连接选项Description描述
maxPoolSize The maximum number of connections in the connection pool. 连接池中的最大连接数。The default value is 100.默认值为100
minPoolSize The minimum number of connections in the connection pool. 连接池中的最小连接数。The default value is 0. 默认值为0
Note
The minPoolSize option is not supported by all drivers. 并非所有驱动程序都支持minPoolSize选项。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 multiplies the maxPoolSize value to, to provide the maximum number of threads allowed to wait for a connection to become available from the pool. 驱动程序将maxPoolSize值乘以的一个数字,以提供允许等待连接从池中变为可用的最大线程数。For default values, see the driver 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 driver documentation.有关默认值,请参阅驱动程序文档。
This option is not supported by all drivers. 并非所有驱动程序都支持此选项。

Write Concern Options写入关注选项

Write concern describes the level of acknowledgment requested from MongoDB. 写入关注描述了MongoDB请求的确认级别。The write concern option is supported by the:以下各项支持写入问题选项:

You can specify the write concern both in the connection string and as a parameter to methods like insert or update. 您可以在连接字符串中指定写关注点,也可以将其作为insertupdate等方法的参数。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:以下到副本集的连接字符串指定"majority"写入关注和使用wtimeoutMS写入关注参数的5秒超时:

mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&w=majority&wtimeoutMS=5000
Connection Option连接选项Description描述
w Corresponds to the write concern w Option. 对应于写入问题w选项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.w选项请求确认写入操作已传播到指定数量的mongod实例或具有指定标记的mongod实例。
You can specify a number, the string majority, or a tag set.可以指定numbermajority字符串或标记集
For details, see w Option. 有关详细信息,请参阅w选项
wtimeoutMS Corresponds to the write concern wtimeout. 对应于写入问题wtimeoutwtimeoutMS specifies a time limit, in milliseconds, for the write concern.指定写入问题的时间限制(以毫秒为单位)。
When wtimeoutMS is 0, write operations will never time out. wtimeoutMS0时,写入操作将永远不会超时。For more information, see wtimeout. 有关更多信息,请参阅wtimeout
journal Corresponds to the write concern j Option option. 对应于写入关注j选项The journal option requests acknowledgement from MongoDB that the write operation has been written to the journal. journal选项请求MongoDB确认写入操作已写入日志For details, see j Option.有关详细信息,请参阅j选项
If you set journal to true, and specify a w value less than 1, journal prevails. 如果将journal设置为true,并指定一个小于1w值,则以journal为准。

For more information, see Write Concern.有关更多信息,请参阅写入关注

readConcern Options

For 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
Connection Option连接选项Description描述
readConcernLevel The level of isolation. 隔离级别。Can accept one of the following values:可以接受以下值之一: This connection string option is not available for mongosh. 此连接字符串选项不适用于mongoshSpecify the read concern as an option to the specific operation. 将读取关注指定为特定操作的选项

For more information, see Read Concern.有关更多信息,请参阅阅取关注

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.这些参数允许您在连接字符串中按每个连接指定读取首选项。

Note

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. 一旦找到,该规范将用于查找所有符合条件的匹配成员,并忽略任何剩余的readPreferenceTagFor details, see Order of Tag Matching.有关详细信息,请参阅标记匹配顺序

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. 包含读取操作的多文档事务必须使用读取首选项primaryAll operations in a given transaction must route to the same member.给定事务中的所有操作都必须路由到同一成员。
This connection string option is not available for the mongo shell. 此连接字符串选项不适用于mongo shell。See cursor.readPref() and Mongo.setReadPref() instead. 请参阅cursor.readPref()Mongo.setReadPref()
maxStalenessSeconds Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. 以秒为单位指定在客户端停止使用辅助进行读取操作之前,辅助的过时程度。For details, see Read Preference maxStalenessSeconds.有关详细信息,请参阅读取首选项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. maxStalenessSeconds的最小值为90秒。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. 指定0到90秒之间的值将产生错误。MongoDB驱动程序将maxStalenessSeconds-1视为“无最大过时”,与省略maxStalenessSeconds时相同。
Important
To use maxStalenessSeconds, all of the MongoDB instances in your deployment must be using MongoDB 3.4 or later. 要使用maxStalenessSeconds,部署中的所有MongoDB实例都必须使用MongoDB 3.4或更高版本。If any instances are on an earlier version of MongoDB, the driver or mongod / mongos will raise an error. 如果任何实例在早期版本的MongoDB上,驱动程序或mongod/mongos将引发错误。
readPreferenceTags Specifies the tags document as a comma-separated list 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 connection string.要指定标签文档{ "dc": "ny", "rack": "r1" },请在连接字符串中使用readPreferenceTags=dc:ny,rack:r1
  • To specify an empty tags document { }, use readPreferenceTags= without setting the value.若要指定空标记文档{ },请使用readPreferenceTags=而不设置值。
To specify a list of tag documents, use multiple readPreferenceTags. 若要指定标记文档的列表,请使用多个readPreferenceTagsFor example, readPreferenceTags=dc:ny,rack:r1&readPreferenceTags=.例如:readPreferenceTags=dc:ny,rack:r1&readPreferenceTags=
Order matters when using multiple readPreferenceTags. 使用多个readPreferenceTags时,顺序很重要。The readPreferenceTags are tried in order until a match is found. For details, see Order of Tag Matching.将按顺序尝试readPreferenceTags,直到找到匹配项。有关详细信息,请参阅标记匹配顺序
This connection string option is not available for the mongo shell. 此连接字符串选项不适用于mongo shell。See cursor.readPref() and Mongo.setReadPref() instead. 请参阅cursor.readPref()Mongo.setReadPref()

For more information, see Read preferences.有关详细信息,请参阅读取首选项

Authentication Options身份验证选项

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.以下到副本集的连接字符串指定到admin数据库的authSource。也就是说,用户凭据是根据admin数据库进行身份验证的。

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

If the username or password includes the following characters:如果用户名或密码包含以下字符:

$ : / ? # [ ] @

those characters must be converted using percent encoding.这些字符必须使用百分比编码进行转换。

Connection Option连接选项Description描述
authSource Specify the database name associated with the user's credentials. 指定与用户凭据关联的数据库名称。If authSource is unspecified, authSource defaults to the defaultauthdb specified in the connection string. 如果未指定authSource,则authSource默认为连接字符串中指定的defaultauthdbIf defaultauthdb is unspecified, then authSource defaults to admin.如果未指定defaultauthdb,则authSource默认为admin
The PLAIN (LDAP), GSSAPI (Kerberos), and MONGODB-AWS (IAM) authentication mechanisms require that authSource be set to $external, as these mechanisms delegate credential storage to external services.PLAIN(LDAP)、GSSAPI(Kerberos)和MONGODB-AWS(IAM)身份验证机制要求将authSource设置为$external,因为这些机制将凭据存储委派给外部服务。
MongoDB will ignore authSource values if no username is provided, either in the connection string or via the --username parameter. 如果没有在连接字符串中或通过--username参数提供用户名,MongoDB将忽略authSource值。
authMechanism Default: SCRAM-SHA-256 Specify the authentication mechanism that MongoDB uses to authenticate the connection. 指定MongoDB用于对连接进行身份验证的身份验证机制。If you don't specify an authMechanism but provide user credentials, MongoDB attempts to use SCRAM-SHA-256. If this fails, it falls back to SCRAM-SHA-1. 如果您没有指定authMechanism,但提供了用户凭据,MongoDB会尝试使用SCRAM-SHA-256。如果失败,则返回SCRAM-SHA-1。 Only MongoDB Enterprise mongod and mongos instances provide GSSAPI (Kerberos) and PLAIN (LDAP) mechanisms.只有MongoDB Enterprise mongodmongos实例提供GSSAPI(Kerberos)和PLAIN(LDAP)机制。
To use MONGODB-X509, you must have TLS/SSL Enabled.要使用MONGODB-X509,必须启用TLS/SSL。
To use MONGODB-AWS, you must be connecting to a MongoDB Atlas cluster which has been configured to support authentication via AWS IAM credentials (i.e. an AWS access key ID and a secret access key, and optionally an AWS session token). 要使用MONGODB-AWS,您必须连接到MONGODB Atlas集群,该集群已配置为支持通过AWS IAM凭据进行身份验证(即AWS访问键ID和秘密访问键,以及可选的AWS会话令牌)。The MONGODB-AWS authentication mechanism requires that the authSource be set to $external.MONGODB-AWS身份验证机制要求authSource设置为$external
When using MONGODB-AWS, provide your AWS access key ID as the username and the secret access key as the password. 使用MONGODB-AWS时,请提供您的AWS访问键ID作为用户名,并提供机密访问键作为密码。If using an AWS session token as well, provide it with the AWS_SESSION_TOKEN authMechanismProperties value. 如果也使用AWS会话令牌,请为其提供AWS_session_tokenauthMechanismProperties值。
Note
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. 这些字符必须使用百分比编码进行转换。
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 mongosh will use these environment variable values to authenticate; you do not need to specify them in the connection string.或者,如果AWS访问键ID、秘密访问键或会话令牌是使用各自的AWS IAM环境变量在您的平台上定义的,mongosh将使用这些环境变量值进行身份验证;您不需要在连接字符串中指定它们。
See Connect to an Atlas Cluster for example usage of the MONGODB-AWS authentication mechanism using both a connection string and the environment variables method.有关MONGODB-AWS身份验证机制使用连接字符串和环境变量方法的示例,请参阅连接到Atlas集群
See Authentication for more information about the authentication system in MongoDB. 有关MongoDB中身份验证系统的更多信息,请参阅身份验证Also consider Use x.509 Certificates to Authenticate Clients for more information on x509 authentication. 有关x509身份验证的更多信息,请考虑使用x.509证书对客户端进行身份验证
authMechanismProperties Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs.将指定authMechanism的属性指定为逗号分隔的键值对列表。
Possible key-value pairs are:可能的键值对有:
SERVICE_NAME:<string>
Set the Kerberos service name when connecting to Kerberized MongoDB instances. 在连接到Kerberized MongoDB实例时设置Kerberos服务名称。This value must match the service name set on MongoDB instances to which you are connecting. 该值必须与您正在连接的MongoDB实例上设置的服务名称相匹配。Only valid when using the GSSAPI authentication mechanism.仅在使用GSSAPI身份验证机制时有效。
SERVICE_NAME defaults to mongodb for all clients and MongoDB instances. 对于所有客户端和MongoDB实例,SERVICE_NAME默认为mongodbIf you change the saslServiceName setting on a MongoDB instance, you must set SERVICE_NAME to match that setting. 如果更改MongoDB实例上的saslServiceName设置,则必须将SERVICE_NAME设置为与该设置匹配。Only valid when using the GSSAPI authentication mechanism. 仅在使用GSSAPI身份验证机制时有效。
CANONICALIZE_HOST_NAME:true|false
Canonicalize the hostname of the client host machine when connecting to the Kerberos server. 在连接到Kerberos服务器时规范客户端主机的主机名。This may be required when hosts report different hostnames than what is in the Kerberos database. Defaults to false. 当主机报告的主机名与Kerberos数据库中的主机名不同时,可能需要这样做。默认为falseOnly valid when using the GSSAPI authentication mechanism.仅在使用GSSAPI身份验证机制时有效。
SERVICE_REALM:<string>
Set the Kerberos realm for the MongoDB service. 为MongoDB服务设置Kerberos领域。This may be necessary to support cross-realm authentication where the user exists in one realm and the service in another. 这对于支持跨领域身份验证可能是必要的,其中用户存在于一个领域,服务存在于另一个领域。Only valid when using the GSSAPI authentication mechanism.仅在使用GSSAPI身份验证机制时有效。
AWS_SESSION_TOKEN:<security_token>
Set the AWS session token for authentication with temporary credentials when using an AssumeRole request, or when working with AWS resources that specify this value such as Lambda. 在使用AssumeRole请求时,或在使用指定该值的AWS资源(如Lambda)时,设置AWS会话令牌以使用临时凭据进行身份验证。Only valid when using the MONGODB-AWS authentication mechanism. 仅在使用MONGODB-AWS身份验证机制时有效。You must have an AWS access key ID and a secret access key as well. 您必须有一个AWS访问键ID和一个秘密访问键。See Connect to an Atlas Cluster for example usage.有关用法示例,请参阅连接到Atlas群集
gssapiServiceName Set the Kerberos service name when connecting to Kerberized MongoDB instances. 在连接到Kerberized MongoDB实例时设置Kerberos服务名称。This value must match the service name set on MongoDB instances to which you are connecting.该值必须与您正在连接的MongoDB实例上设置的服务名称相匹配。
gssapiServiceName defaults to mongodb for all clients and MongoDB instances. 对于所有客户端和mongodb实例,默认为mongodb。If you change saslServiceName setting on a MongoDB instance, you must set gssapiServiceName to match that setting.如果更改MongoDB实例上的saslServiceName设置,则必须将gssapiServiceName设置为与该设置匹配。
gssapiServiceName is a deprecated aliases for authMechanismProperties=SERVICE_NAME:mongodb. 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.MongoDB提供了以下选项来配置MongoDB驱动程序和mongos实例如何选择要直接进行读写操作的服务器。

Connection Option连接选项Description描述
localThresholdMS The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. 用于在多个合适的MongoDB实例中进行选择的延迟窗口的大小(以毫秒为单位)。Default: 15 milliseconds.:15毫秒。
All drivers use localThresholdMS. 所有驱动程序都使用localThresholdMSUse the localThreshold alias when specifying the latency window size to mongos. 在为mongos指定延迟窗口大小时,请使用localThreshold别名。
serverSelectionTimeoutMS Specifies how long (in milliseconds) to block for server selection before throwing an exception. 指定在引发异常之前阻止服务器选择的时间(以毫秒为单位)。Default: 30,000 milliseconds.:30000毫秒。
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. 如果为true,则指示驱动程序在服务器选择失败后扫描MongoDB部署一次,然后选择服务器或引发错误。When false, the driver blocks and searches for a server up to the serverSelectionTimeoutMS value. Default: true.如果为false,则驱动程序会阻止并搜索服务器,直到serverSelectionTimeoutMS值。默认值:true
Multi-threaded drivers and mongos do not support serverSelectionTryOnce.多线程驱动程序和mongos不支持serverSelectionTryOnce
heartbeatFrequencyMS heartbeatFrequencyMS controls when the driver checks the state of the MongoDB deployment. 控制驱动程序何时检查MongoDB部署的状态。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.单线程驱动程序:60秒。
  • Multi-threaded drivers: 10 seconds.多线程驱动程序:10秒。
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:指定自定义应用程序名称。应用程序名称显示在: The appName connection option is available for:
retryReads Enables 启用retryable reads.
Possible values are:可能的值为:
  • true. Enables retryable reads for the connection.。为连接启用可重试的读取。
    Official MongoDB drivers compatible with MongoDB Server 4.2 and later default to true.与MongoDB Server 4.2及更高版本兼容的官方MongoDB驱动程序默认为true
  • false. Disables retryable reads for the connection.。禁用连接的可重试读取。
mongosh does not support retryable reads. 不支持可重试读取。
New in version 4.2. 4.2版新增。
retryWrites Enable retryable writes.启用可重试写入
Possible values are:可能的值为:
  • true. Enables retryable writes for the connection.为连接启用可重试的写入。
    Official MongoDB 4.2+ compatible drivers default to true.MongoDB 4.2+官方兼容驱动程序默认为true
  • false. Disables retryable writes for the connection.禁用连接的可重试写入。
    Official MongoDB 4.0 and 3.6-compatible drivers default to false.MongoDB 4.0和3.6兼容的官方驱动程序默认为false
MongoDB drivers retry transaction commit and abort operations regardless of the value of retryWrites. MongoDB驱动程序重试事务提交和中止操作,而不考虑retryWrites的值。For more information on transaction retryability, see Transaction Error Handling. 有关事务可重试性的更多信息,请参阅事务错误处理
uuidRepresentation Possible values are:可能的值为:
standard
The standard binary representation.标准二进制表示法。
csharpLegacy
The default representation for the C# driver.C#驱动程序的默认表示形式。
javaLegacy
The default representation for the Java driver.Java驱动程序的默认表示形式。
pythonLegacy
The default representation for the Python driver.Python驱动程序的默认表示形式。
For the default, see the Drivers documentation for your driver. 有关默认设置,请参阅驱动程序的驱动程序文档。
Note
Not all drivers support the uuidRepresentation option. 并非所有驱动程序都支持uuidRepresentation选项。For information on your driver, see the drivers documentation. 有关驱动程序的信息,请参阅驱动程序文档。

Examples实例

The following provide example URI strings for common connection targets.下面提供了常见连接目标的URI字符串示例。

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:以下用户使用密码moon以用户sysop的身份连接并登录到admin数据库:

mongodb://sysop:moon@localhost

records Database数据库

The following connects and logs in to the records database as user sysop with the password moon:以下用户使用密码moon作为用户sysop连接并登录到records数据库:

mongodb://sysop:moon@localhost/records

UNIX Domain Socket域套接字

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
Note

Not all drivers support UNIX domain sockets. 并非所有驱动程序都支持UNIX域套接字。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:下面连接到一个具有两个成员的复制集,一个在db1.example.net上,另一个在db2.example.net上:

Note

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

Replica Set with Members on localhostlocalhost具有成员的副本集

The following connects to a replica set with three members running on localhost on ports 27017, 27018, and 27019:以下连接到一个复制副本集,其中有三个成员在本地主机上的端口270172701827019上运行:

Note

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

Replica Set with Read Distribution具有读取分发的副本集

The following connects to a replica set with three members and distributes reads to the secondaries:以下连接到一个有三个成员的复制副本集,并将读取分发到secondary

Note

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

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 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.对于副本集,指定副本集配置中列出的mongod实例的主机名。

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:以下连接到具有三个mongos实例的分片集群:

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

MongoDB Atlas ClusterMongoDB Atlas集群

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 MONGODB-AWS authentication mechanism and the $external authSource, as shown in this example.以这种方式使用AWS IAM凭据连接到Atlas使用MONGODB-AWS身份验证机制$externalauthSource,如本例所示。

If using an AWS session token, as well, provide it with the AWS_SESSION_TOKEN authMechanismProperties value, as follows:如果也使用AWS会话令牌,请为其提供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>'
Note

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'