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

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

Connection String Formats连接字符串格式

You can specify the MongoDB connection string 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主机。

  • 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.这些字符必须使用百分比编码进行转换。

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

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

/defaultauthdb

Optional. 可选。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,客户端将尝试向管理数据库验证指定的用户。

?<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.如果连接字符串未指定数据库,你就必须在最后一个host和问号(?)之间指定斜线(/),这是一系列选项的开始。

DNS Seed List Connection FormatDNS种子列表连接格式

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. +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实例。

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

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.如果父域和主机名不匹配,您将无法连接。

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.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 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 will fail if there is no available DNS with records that correspond to the hostname identified in the connection string. 如果没有与连接字符串中标识的主机名对应的记录可用的DNS,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)选项设置为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=false(或ssl=false)将tls(或等效的ssl)选项显式设置为false,可以覆盖此行为。

Tip提示
See:

Connect to a Replica Set Using the DNS Seedlist Connection Format使用DNS种子列表连接格式连接到副本集 provides an example of connecting mongosh to a replica set using the DNS Seed list Connection Format.提供了使用DNS种子列表连接格式将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, or the version 4.2 or later legacy mongo shell.使用mongosh或4.2或更高版本的传统mongo shell时,选项名称不区分大小写。
  • The option name is case sensitive when using a version 4.0 and earlier legacy mongo shell.使用版本4.0及更早的旧版mongo shell时,选项name区分大小写。
  • The value is always case sensitive.value始终区分大小写。

Separate options with the ampersand (i.e. &) character name1=value1&name2=value2. 分隔选项用符号ampersand(即&)字符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.如果mongod副本集的成员,则指定副本集的名称。

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 mongo shell specifies additional tls/ssl options from the command-line, use the --tls command-line option instead.如果mongo 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 mongo shell specifies additional tls/ssl options from the command-line, use the --ssl command-line option instead.如果mongo 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.指定包含客户端TLS/SSL X.509证书或客户端TLS/SSL证书和密钥的本地.pem文件的位置。

The client presents this file to the mongod/mongos instance.客户端将此文件呈现给mongod/mongos实例。

Changed in version 4.4.在版本4.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描述
connectTimeoutMSThe 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.请参阅驱动程序文档。
socketTimeoutMSThe 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)(MongoDB 3.6或更高版本提供)
  • zstd (Available in MongoDB 4.2 or greater)(MongoDB 4.2或更高版本提供)

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.支持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 - 9

Increasing level of compression but at the cost of speed, with:提高压缩级别,但以牺牲速度为代价,包括:

  • 1 providing the best speed but least compression, and提供最佳速度但压缩最少,以及
  • 9 providing the best compression but at the slowest speed.提供最佳压缩,但速度最慢。

Not supported by 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描述
maxPoolSizeThe 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:以下到副本集的连接字符串使用wtimeoutMS写入关注参数指定"majority"写入问题和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.可以指定number、字符串majority标记集

For details, see w Option.有关详细信息,请参阅w选项。

wtimeoutMS

Corresponds to the write concern wtimeout. 对应于写入问题wtimeoutwtimeoutMS specifies a time limit, in milliseconds, for the write concern.wtimeoutMS指定写入问题的时间限制(以毫秒为单位)

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,并指定小于1的w值,则以journal为准。

If you set journal to true, and the mongod does not have journaling enabled, as with storage.journal.enabled, then MongoDB will error.如果将journal设置为true,并且mongod没有像storage.journal.enabled那样启用日志记录,则MongoDB将出错。

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. 一旦找到,该规范将用于查找所有符合条件的匹配成员,并忽略任何剩余的readPreferenceTagsFor 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. 指定0到90秒之间的值将产生错误。MongoDB drivers treat a maxStalenessSeconds value of -1 as "no max staleness", the same as if maxStalenessSeconds is omitted.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=.

Order matters when using multiple readPreferenceTags. 使用多个readPreferenceTags时,顺序很重要。The readPreferenceTags are tried in order until a match is found. readPreferenceTags会按顺序尝试,直到找到匹配项。For details, see Order of Tag Matching.有关详细信息,请参阅标记匹配的顺序

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. 以下副本集的连接字符串指定了admin数据库的authSourceThat 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
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

Specify the authentication mechanism that MongoDB will use to authenticate the connection. 指定MongoDB将用于验证连接的身份验证机制。Possible values include:可能的值包括:

MongoDB 4.0 removes support for the MONGODB-CR authentication mechanism. MongoDB 4.0取消了对MongoDB-CR身份验证机制的支持。You cannot specify MONGODB-CR as the authentication mechanism when connecting to MongoDB 4.0+ deployments.连接到MONGODB 4.0+部署时,不能将MONGODB-CR指定为身份验证机制。

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_TOKENauthMechanismProperties value.如果同时使用AWS会话令牌,请为其提供AWS_SESSION_TOKEN authMechanismProperties值。

Note注意

If the AWS access key ID, secret access key, or 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 variablesmongosh will use these environment variable values to authenticate; you do not need to specify them in the connection string.或者,如果平台上使用各自的AWS IAM环境变量定义了AWS访问密钥ID、秘密访问密钥或会话令牌,则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.还考虑使用X.509证书来验证客户端,以获得关于X509身份验证的更多信息。

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实例,默认为mongodbIf you change the saslServiceName setting on a MongoDB instance, you must set SERVICE_NAME to match that setting. 如果更改MongoDB实例上的saslServiceName设置,则必须将服务名称设置为与该设置匹配。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. 当主机报告的主机名与Kerberos数据库中的主机名不同时,可能需要这样做。Defaults to false. 默认为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实例,默认为mongodbIf 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别名。

serverSelectionTimeoutMSSpecifies 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. 如果为false,则驱动程序将阻止并搜索服务器serverSelectionTimeoutMS值以下的服务器。Default: true.默认值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 only applicable when provided to a MongoDB Driver. appName连接选项仅在提供给MongoDB驱动程序时适用。This parameter has no effect when supplied to a client application such as MongoDB Compass or mongosh.当提供给客户端应用程序(如MongoDB Compassmongosh)时,此参数无效。

New in version 4.0.在版本4.0中新增

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

mongodb://sysop:moon@localhost

records Database数据库

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

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:以下内容连接到一个包含三个成员的副本集,并将读取内容分发到二级副本

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 Cluster群集

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身份验证机制$external authSource,如本例所示。

If using an AWS session token, as well, provide it with the AWS_SESSION_TOKENauthMechanismProperties value, as follows:如果同时使用AWS会话令牌,请为其提供AWS_SESSION_TOKENauthMechanismProperties值,如下所示:

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-AWSauthentication 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'
←  System CollectionsCollation →