Docs Home / mongosh

Connect to a Deployment连接到部署

This page shows how to use the MongoDB Shell to connect to a MongoDB deployment. You can connect to a MongoDB Atlas cloud-hosted deployment, connect to a local deployment, or connect to another remote host with MongoDB Shell.此页面显示了如何使用MongoDB Shell连接到MongoDB部署。您可以连接到MongoDB Atlas云托管部署,连接到本地部署,或使用MongoDB Shell连接到另一个远程主机。

Prerequisites先决条件

To use the MongoDB Shell, you must have a MongoDB deployment to connect to.要使用MongoDB Shell,您必须有一个MongoDB部署才能连接。

Supported MongoDB Versions支持的MongoDB版本

You can use the MongoDB Shell to connect to MongoDB version 7.0 or greater.您可以使用MongoDB Shell连接到MongoDB 7.0或更高版本。

Install mongosh安装mongosh

These procedures assume you have already installed mongosh. For more information about installing mongosh, refer to Install mongosh.这些过程假设您已经安装了mongosh。有关安装mongosh的更多信息,请参阅安装mongosch

Connect to a MongoDB Atlas Deployment连接到MongoDB Atlas部署

You can connect to your MongoDB Atlas deployment directly from your shell.您可以直接从shell连接到MongoDB Atlas部署。

1

Get your Atlas Connection String获取Atlas连接字符串

You need an Atlas connection string to connect from MongoDB Shell. You can get the Atlas connection string in the Atlas UI.您需要一个Atlas连接字符串才能从MongoDB Shell连接。您可以在Atlas UI中获取Atlas连接字符串。

Refer to the Find Your MongoDB Atlas Connection String guide for details.有关详细信息,请参阅查找MongoDB Atlas连接字符串指南。

2

Set Your Database Credentials设置数据库凭据

If you haven't already created a database user, you must set a username and password. 如果您尚未创建数据库用户,则必须设置用户名和密码。To connect to Atlas, pass your username with the Atlas connection string. After you issue the connect command, the shell prompts for your password.要连接到Atlas,请将用户名与Atlas连接字符串一起传递。发出connect命令后,shell会提示您输入密码。

3

Connect to MongoDB Atlas with mongosh使用mongosh连接到MongoDB Atlas

To establish your connection, run the mongosh command with your connection string and options to establish the connection.要建立连接,请使用连接字符串和选项运行mongosh命令以建立连接。

The connection string includes the following elements:连接字符串包括以下元素:

  • Your cluster name群集名称
  • A hash哈希
  • A flag for the API versionAPI版本的标志
  • A flag for the username you want to use to connect用于连接的用户名的标志

It resembles the following string:它类似于以下字符串:

mongosh "mongodb+srv://YOUR_CLUSTER_NAME.YOUR_HASH.mongodb.net/" --apiVersion YOUR_API_VERSION --username YOUR_USERNAME

Note

Learn More了解更多

You can use other connection security options to connect to Atlas via mongosh. For information on connecting with a private IP for peering or a Private Endpoint connection, refer to the Atlas Connect via mongosh documentation.您可以使用其他连接安全选项通过mongosh连接到Atlas。有关使用专用IP进行对等连接或专用端点连接的信息,请参阅Atlas Connect via mongosh文档。

Connect to a Local Deployment on the Default Port连接到默认端口上的本地部署

To connect to a MongoDB deployment running on localhost with default port 27017, run mongosh without any options:要连接到在本地主机上运行的MongoDB部署,默认端口为27017,请运行mongosh,不带任何选项:

mongosh

This is equivalent to the following command:这相当于以下命令:

mongosh "mongodb://localhost:27017"

Connect to a Local Deployment on a Non-Default Port连接到非默认端口上的本地部署

To specify a port to connect to on localhost, you can use either:要在本地主机上指定要连接的端口,您可以使用以下任一方法:

For example, the following commands connect to a deployment running on localhost port 28015:例如,以下命令连接到在localhost端口28015上运行的部署:

mongosh "mongodb://localhost:28015"
mongosh --port 28015

Connect to a Deployment on a Remote Host连接到远程主机上的部署

To specify a remote host and port, you can use either:要指定远程主机和端口,您可以使用以下任一方法:

  • A connection string with the chosen host and port.具有所选主机和端口的连接字符串
  • The --host and --port command-line options. If you omit the --port option, mongosh uses the default port 27017.--host--port命令行选项。如果省略--port选项,mongosh将使用默认端口27017

For example, the following commands connect to a MongoDB deployment running on host mongodb0.example.com and port 28015:例如,以下命令连接到在主机mongodb0.example.com和端口28015上运行的MongoDB部署:

mongosh "mongodb://mongodb0.example.com:28015"
mongosh --host mongodb0.example.com --port 28015

Note

Connect to MongoDB Atlas连接到MongoDB Atlas

If your remote host is an Atlas cluster, you can copy your connection string from the Atlas UI. 如果远程主机是Atlas集群,则可以从Atlas UI复制连接字符串。To learn more, see Connect to a Cluster in the Atlas documentation.要了解更多信息,请参阅Atlas文档中的“连接到集群”

Specify Connection Options指定连接选项

Specify different connection options to connect to different types of deployments.指定不同的连接选项以连接到不同类型的部署。

Connect With Authentication通过身份验证连接

To connect to a MongoDB deployment that requires authentication, use the --username and --authenticationDatabase options. 要连接到需要身份验证的MongoDB部署,请使用--username--authenticationDatabase选项。mongosh prompts you for a password, which it hides as you type.mongosh会提示您输入密码,并在您键入时隐藏该密码。

For example, to authenticate as user alice on the admin database, run the following command:例如,要在admin数据库上以用户alice身份进行身份验证,请运行以下命令:

mongosh "mongodb://mongodb0.example.com:28015" --username alice --authenticationDatabase admin

To provide a password as part of the connection command instead of using the prompt, use the --password option. Use this option for programmatic usage of mongosh, like a driver.要在连接命令中提供密码而不是使用提示符,请使用--password选项。将此选项用于mongosh的编程使用,如驱动程序。

Tip

Connect with OpenID Connect使用OpenID连接

To connect to a deployment using OpenID Connect, use the --authenticationMechanism option and set it to MONGODB-OIDC. 要使用OpenID连接连接到部署,请使用--authenticationMechanism选项并将其设置为MONGODB-OIDCmongosh redirects you to a browser where you enter your identity provider's log-in information.mongosh会将您重定向到一个浏览器,您可以在其中输入身份提供者的登录信息。

Note

By default, mongosh requests the oidc and offline_access scopes from the identity provider (IdP). If the IdP supports neither oidc nor offline_access, mongosh does not request those scopes. 默认情况下,mongosh向身份提供者(IdP)请求oidcoffline_access作用域。如果IdP既不支持oidc也不支持offline_accessmongosh就不会请求这些作用域。If the IdP supports oidc but not offline_access, you must re-authenticate frequently. 如果IdP支持oidc但不支持offline_access,则必须经常重新进行身份验证。To learn more, see oidcIdentityProviders Fields.要了解更多信息,请参阅oidcIdentityProviders字段

For example, the following connects to a local deployment using MONGODB-OIDC:例如,以下内容使用MONGODB-OIDC连接到本地部署:

mongosh "mongodb://localhost/" --authenticationMechanism MONGODB-OIDC

Connect with LDAP使用LDAP连接

To connect to a deployment using LDAP:要使用LDAP连接到部署:

Warning

When you use one-time passwords with LDAP authentication, adding the connection string options maxPoolSize=1&srvMaxHosts=1 to your connection string is recommended to reduce the potential for connection failures.当您在LDAP身份验证中使用一次性密码时,建议将连接字符串选项maxPoolSize=1&srvMaxHosts=1添加到连接字符串中,以减少连接失败的可能性。

Include the --host and --port of the MongoDB deployment, along with any other options relevant to your deployment.包括MongoDB部署的--host--port,以及与部署相关的任何其他选项。

For example, the following operation authenticates to a MongoDB deployment running with LDAP authentication and authorization:例如,以下操作对使用LDAP身份验证和授权运行的MongoDB部署进行身份验证:

mongosh --username alice@dba.example.com --password  --authenticationDatabase '$external' --authenticationMechanism "PLAIN"  --host "mongodb.example.com" --port 27017

Connect to a Replica Set连接到副本集

To connect to a replica set, you can either:要连接到副本集,您可以:

Important

When a replica set runs in Docker, it might expose only one MongoDB endpoint. In this case, the replica set is not discoverable, and specifying directConnection=false can prevent your application from connecting to it.当一个副本集在Docker中运行时,它可能只暴露一个MongoDB端点。在这种情况下,无法发现副本集,指定directConnection=false会阻止应用程序连接到它。

In a test or development environment, you can connect to the replica set by specifying directConnection=true in your connection URI. 在测试或开发环境中,您可以通过在连接URI中指定directConnection=true来连接到副本集。In a production environment, we recommend configuring the cluster to make each MongoDB instance accessible outside of the Docker virtual network.在生产环境中,我们建议配置集群,使每个MongoDB实例都可以在Docker虚拟网络之外访问。

Option 1: DNS Seedlist Format选项1:DNS种子列表格式

To use the DNS seedlist connection format, include the +srv modifier in your connection string.要使用DNS种子列表连接格式,请在连接字符串中包含+srv修饰符。

For example, to connect to a replica set on server.example.com, run the following command:例如,要连接到server.example.com上的副本集,请运行以下命令:

mongosh "mongodb+srv://server.example.com/"

Note

+srv TLS Behavior行为

When you use the +srv connection string modifier, MongoDB automatically sets the --tls connection option to true. To override this behavior, set --tls to false.当您使用+srv连接字符串修饰符时,MongoDB会自动将--tls连接选项设置为true。要覆盖此行为,请将--tls设置为false

Option 2: Specify Members in Connection String选项2:在连接字符串中指定成员

You can specify individual replica set members in the connection string.您可以在连接字符串中指定单个副本集成员。

For example, to connect to a three-member replica set named replA, run the following command:例如,要连接到名为replA的三成员副本集,请运行以下命令:

mongosh "mongodb://mongodb0.example.com.local:27017,mongodb1.example.com.local:27017,mongodb2.example.com.local:27017/?replicaSet=replA"

Note

directConnection Parameter Added AutomaticallydirectConnection参数已自动添加

When you specify individual replica set members in the connection string, mongosh automatically adds the directConnection=true parameter, unless at least one of the following is true:当您在连接字符串中指定单个副本集成员时,mongosh会自动添加directConnection=true参数,除非以下至少有一个为true

  • The replicaSet query parameter is present in the connection string.replicaSet查询参数存在于连接字符串中。
  • The connection string uses the mongodb+srv:// connection string format.连接字符串使用mongodb+srv://连接字符串格式。
  • The connection string contains a seed list with multiple hosts.连接字符串包含一个包含多个主机的种子列表。
  • The connection string already contains a directConnection parameter.连接字符串已包含directConnection参数。

When directConnection=true, the host specified in the connection URI runs all operations and mongosh ignores all read preferences, including explicitly set preferences.directConnection=true时,连接URI中指定的主机将运行所有操作,mongosh将忽略所有读取首选项,包括显式设置的首选项。

Connect Using TLS使用TLS连接

To connect to a deployment using TLS, you can either:要使用TLS连接到部署,您可以:

  • Use the DNS Seedlist Connection Format. The +srv connection string modifier automatically sets the tls option to true for the connection.使用DNS种子列表连接格式+srv连接字符串修饰符会自动将连接的tls选项设置为true

    For example, to connect to a DNS seedlist-defined replica set with tls enabled, run the following command:例如,要连接到启用tls的DNS种子列表定义的副本集,请运行以下命令:

    mongosh "mongodb+srv://server.example.com/"
  • Set the --tls option to true in the connection string.在连接字符串中将--tls选项设置为true

    For example, to enable tls with a connection string option, run the following command:例如,要使用连接字符串选项启用tls,请运行以下命令:

    mongosh "mongodb://mongodb0.example.com:28015/?tls=true"
  • Specify the --tls command-line option.指定--tls命令行选项。

    For example, to connect to a remote host with tls enabled, run the following command:例如,要连接到启用tls的远程主机,请运行以下命令:

    mongosh "mongodb://mongodb0.example.com:28015" --tls

Connect to a Specific Database连接到特定数据库

To connect to a specific default database, specify a database in your connection string URI path. If unspecified by the connection string, the default database is the test database.要连接到特定的默认数据库,请在连接字符串URI路径中指定一个数据库。如果连接字符串未指定,则默认数据库是test数据库。

For example, to connect to a database called qa on localhost, run the following command:例如,要连接到localhost上名为qa的数据库,请运行以下命令:

mongosh "mongodb://localhost:27017/qa"

You can specify the authentication database in your connection string using the authSource connection option. If specified, the client uses this database to verify your user identity and credentials. 您可以使用authSource连接选项在连接字符串中指定身份验证数据库。如果指定,客户端将使用此数据库验证用户身份和凭据。If authSource is unspecified, it defaults to the default database specified in the connection string. 如果未指定authSource,则默认为连接字符串中指定的默认数据库。If both authSource and the default database are unspecified, authSource defaults to the admin database.如果未指定authSource和默认数据库,则authSource默认为admin数据库。

The following connection string sets the default database to myDefaultDB and the authentication database to admin:以下连接字符串将默认数据库设置为myDefaultDB,将身份验证数据库设置为admin

mongodb://myDatabaseUser:D1fficultP%40ssw0rd@mongodb0.example.com:27017/myDefaultDB?authSource=admin

Proxy Settings代理设置

To establish a connection with proxy configurations, you can use the following environment variables:要建立与代理配置的连接,可以使用以下环境变量:

Variable变量Description描述Example示例
MONGODB_PROXYProxy connections to mongodb:// and mongodb+srv:// URLs, such as database clusters.mongodb://mongodb+srv://URL的代理连接,如数据库集群。

The following example sets the MONGODB_PROXY environment variable to proxy all MongoDB connections through a CONNECT proxy located at example.com:8080 with TLS enabled.以下示例设置MONGODB_PROXY环境变量,通过位于example.com:8080的CONNECT代理代理代理所有MONGODB连接,并启用TLS。

export MONGODB_PROXY=https://example.com:8080
HTTP_PROXY

Proxy connections to http:// URLs. HTTP connections are mostly used for OIDC authentication.http://URL的代理连接。http连接主要用于OIDC身份验证。

If you also set HTTPS_PROXY, the value of HTTPS_PROXY takes precedence for all requests.如果还设置了HTTPS_PROXY,则HTTPS_PROXY的值对所有请求都优先。

The following example sets the HTTP_PROXY environment variable to proxy HTTP connections through a CONNECT proxy located at example.com:8080:以下示例将HTTP_PROXY环境变量设置为通过位于example.com:8080的CONNECT代理代理HTTP连接:

export HTTP_PROXY=http://example.com:8080
HTTPS_PROXY

Proxy connections to https:// URLs. HTTPS connections are mostly used for OIDC authentication.代理连接到https://URL。https连接主要用于OIDC身份验证。

If you also set HTTP_PROXY, the value of HTTPS_PROXY takes precedence for all requests.如果还设置了HTTP_PROXY,则HTTPS_PROXY的值对所有请求都优先。

The following example sets the HTTPS_PROXY environment variable to proxy all HTTPS connections through a CONNECT proxy located at localhost:8080 without TLS:以下示例设置HTTPS_PROXY环境变量,通过位于localhost:8080的CONNECT代理代理所有HTTPS连接,不使用TLS:

export HTTPS_PROXY=http://localhost:8080
ALL_PROXYProxy all connections to the specified URL.将所有连接代理到指定的URL。

The following example sets the ALL_PROXY environment variable to proxy all outbound network connections through a Socks5 proxy located at example.com:1234 with credentials included in the URL:以下示例设置ALL_PROXY环境变量,通过位于example.com:1234的Socks5代理代理所有出站网络连接,并在URL中包含凭据:

export ALL_PROXY=socks5://username:password@example.com:1234
NO_PROXYComma-separated list of hostnames that should be excluded from proxying.应排除在代理之外的以逗号分隔的主机名列表。

The following example sets the NO_PROXY environment variable to bypass the proxy for connections to localhost and internal-db.example.com.以下示例设置NO_PROXY环境变量,以绕过连接到localhostinternal-db.example.com的代理。

export NO_PROXY=localhost,internal-db.example.com

Note

mongosh supports the following proxy types:支持以下代理类型:

  • Socks5 proxies代理
  • HTTP proxies代理
  • CONNECT proxies代理
  • PAC URLs that resolve to one of the previously listed proxies解析为前面列出的代理之一的URL

Connect to a Different Deployment连接到其他部署

If you are already connected to a deployment in the MongoDB Shell, you can use the Mongo() or connect() method to connect to a different deployment from within the MongoDB Shell.如果您已经连接到MongoDB Shell中的部署,则可以使用Mongo()connect()方法从MongoDB Shell中连接到其他部署。

To learn how to connect to a different deployment using these methods, see Open a New Connection.要了解如何使用这些方法连接到其他部署,请参阅打开新连接

Verify Current Connection验证当前连接

To verify your current database connection, use the db.getMongo() method.要验证当前的数据库连接,请使用db.getMongo()方法。

The method returns the connection string URI for your current connection.该方法返回当前连接的连接字符串URI

Disconnect from a Deployment断开与部署的连接

To disconnect from a deployment and exit mongosh, perform one of the following actions:要断开与部署的连接并退出mongosh,请执行以下操作之一:

  • Type .exit, exit, or exit().键入.exitexitexit()
  • Type quit or quit().键入quitquit()
  • Press Ctrl + D.Ctrl+D
  • Press Ctrl + C twice.Ctrl+C两次。

Non-genuine Deployments非真实部署

The shell displays a warning message when you connect to non-genuine MongoDB instances. Non-genuine instances may behave differently from the official MongoDB instances due to missing, inconsistent, or incomplete features.当您连接到非正版MongoDB实例时,shell会显示一条警告消息。由于缺少、不一致或不完整的功能,非正版实例的行为可能与官方MongoDB实例不同。

Limitations局限性

  • Kerberos authentication does not allow authMechanismProperties=CANONICALIZE_HOST_NAME:true|false in the connection string. Instead, use either:Kerberos身份验证不允许在连接字符串中使用authMechanismProperties=CANONICALIZE_HOST_NAME:true|false 。请使用以下任一方法:

    • authMechanismProperties=CANONICALIZE_HOST_NAME:forward
    • authMechanismProperties=CANONICALIZE_HOST_NAME:forwardAndReverse
    • authMechanismProperties=CANONICALIZE_HOST_NAME:none
  • mongosh currently only supports the zlib compressor. mongosh目前只支持zlib压缩器。The following compressors are not supported:不支持以下压缩器:

    • zstd
    • snappy
  • Starting in mongosh 2.0.0:mongosh 2.0.0开始:

    For boolean values in connection strings, you:对于连接字符串中的布尔值,您可以:

    • must use true or false.必须使用truefalse
    • cannot use 1, y, yes, or t instead of true.不能使用1yyest代替true
    • cannot use -1, 0, n, no, or f instead of false.不能使用-10nnof代替false