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部署才能连接。
For a free cloud-hosted deployment, you can use MongoDB Atlas.对于免费的云托管部署,您可以使用MongoDB Atlas。To learn how to run a local MongoDB deployment, see Install MongoDB.要了解如何运行本地MongoDB部署,请参阅安装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
mongoshThese 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部署。
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连接字符串指南。
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会提示您输入密码。
Connect to MongoDB Atlas with mongosh使用mongosh连接到MongoDB Atlas
mongoshTo 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_USERNAMENote
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 要连接到在本地主机上运行的MongoDB部署,默认端口为mongosh without any options: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:要在本地主机上指定要连接的端口,您可以使用以下任一方法:
A connection string with the chosen port具有所选端口的连接字符串The--portcommand-line option--port命令行选项
For example, the following commands connect to a deployment running on localhost port 28015:例如,以下命令连接到在localhost端口28015上运行的部署:
mongosh "mongodb://localhost:28015"
mongosh --port 28015Connect 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--hostand--portcommand-line options. If you omit the--portoption,mongoshuses 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 要连接到需要身份验证的MongoDB部署,请使用--username and --authenticationDatabase options. --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
To enforce authentication on a deployment, see Enable Access Control.要在部署上强制身份验证,请参阅启用访问控制。To provision access to a MongoDB deployment, see Database Users.要配置对MongoDB部署的访问,请参阅数据库用户。
Connect with OpenID Connect使用OpenID连接
To connect to a deployment using OpenID Connect, use the 要使用OpenID连接连接到部署,请使用--authenticationMechanism option and set it to MONGODB-OIDC. --authenticationMechanism选项并将其设置为MONGODB-OIDC。mongosh 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)请求oidc和offline_access作用域。如果IdP既不支持oidc也不支持offline_access,mongosh就不会请求这些作用域。If the IdP supports 如果IdP支持oidc but not offline_access, you must re-authenticate frequently. 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-OIDCConnect with LDAP使用LDAP连接
To connect to a deployment using LDAP:要使用LDAP连接到部署:
Set将--usernameto a username that respects thesecurity.ldap.authz.queryTemplate, or any configuredsecurity.ldap.userToDNMappingtemplate.--username设置为尊重security.ldap.authz.queryTemplate或任何配置的security.ldap.userToDNMapping模板的用户名。Set将--passwordto the appropriate password. If you do not specify the password to the--passwordcommand-line option,mongoshprompts you for the password.--password设置为适当的密码。如果不在--password命令行选项中指定密码,mongosh会提示您输入密码。Set将--authenticationDatabaseto$external. The$externalargument must be placed in single quotes, not double quotes, to prevent the shell from interpreting$externalas a variable.--authenticationDatabase设置为$external。$external参数必须放在单引号中,而不是双引号中,以防止shell将$external解释为变量。Set将--authenticationMechanismtoPLAIN.--authenticationMechanism设置为PLAIN。
Warning
When you use one-time passwords with LDAP authentication, adding the connection string options 当您在LDAP身份验证中使用一次性密码时,建议将连接字符串选项maxPoolSize=1&srvMaxHosts=1 to your connection string is recommended to reduce the potential for connection failures.maxPoolSize=1&srvMaxHosts=1添加到连接字符串中,以减少连接失败的可能性。
Include the 包括MongoDB部署的--host and --port of the MongoDB deployment, along with any other options relevant to your deployment.--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 27017Connect to a Replica Set连接到副本集
To connect to a replica set, you can either:要连接到副本集,您可以:
Use the DNS Seedlist Connection Format.使用DNS种子列表连接格式。Explicitly specify the replica set name and members in the connection string.在连接字符串中明确指定副本集名称和成员。
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 当一个副本集在Docker中运行时,它可能只暴露一个MongoDB端点。在这种情况下,无法发现副本集,指定directConnection=false can prevent your application from connecting to it.directConnection=false会阻止应用程序连接到它。
In a test or development environment, you can connect to the replica set by specifying 在测试或开发环境中,您可以通过在连接URI中指定directConnection=true in your connection 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 要使用DNS种子列表连接格式,请在连接字符串中包含+srv modifier in your connection string.+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/"
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:
ThereplicaSetquery 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连接字符串已包含directConnectionparameter.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使用DNS种子列表连接格式。+srvconnection string modifier automatically sets thetlsoption totruefor the connection.+srv连接字符串修饰符会自动将连接的tls选项设置为true。For example, to connect to a DNS seedlist-defined replica set with例如,要连接到启用tlsenabled, run the following command:tls的DNS种子列表定义的副本集,请运行以下命令:mongosh "mongodb+srv://server.example.com/"Set the在连接字符串中将--tlsoption totruein the connection string.--tls选项设置为true。For example, to enable例如,要使用连接字符串选项启用tlswith a connection string option, run the following command:tls,请运行以下命令:mongosh "mongodb://mongodb0.example.com:28015/?tls=true"Specify the指定--tlscommand-line option.--tls命令行选项。For example, to connect to a remote host with例如,要连接到启用tlsenabled, 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 要连接到特定的默认数据库,请在连接字符串URI路径中指定一个数据库。如果连接字符串未指定,则默认数据库是test database.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=adminProxy Settings代理设置
To establish a connection with proxy configurations, you can use the following environment variables:要建立与代理配置的连接,可以使用以下环境变量:
MONGODB_PROXY | mongodb:// and mongodb+srv:// URLs, such as database clusters.mongodb://和mongodb+srv://URL的代理连接,如数据库集群。 |
|
HTTP_PROXY |
|
|
HTTPS_PROXY |
|
|
ALL_PROXY |
| |
NO_PROXY |
|
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 如果您已经连接到MongoDB Shell中的部署,则可以使用Mongo() or connect() method to connect to a different deployment from within the 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, orexit()..exit、exit或exit()。Type键入quitorquit().quit或quit()。Press按Ctrl+D。Ctrl+D.Press按Ctrl+C两次。Ctrl+Ctwice.
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 allowKerberos身份验证不允许在连接字符串中使用authMechanismProperties=CANONICALIZE_HOST_NAME:true|falsein the connection string. Instead, use either:authMechanismProperties=CANONICALIZE_HOST_NAME:true|false。请使用以下任一方法:authMechanismProperties=CANONICALIZE_HOST_NAME:forwardauthMechanismProperties=CANONICALIZE_HOST_NAME:forwardAndReverseauthMechanismProperties=CANONICALIZE_HOST_NAME:none
mongoshcurrently only supports thezlibcompressor.mongosh目前只支持zlib压缩器。The following compressors are not supported:不支持以下压缩器:zstdsnappy
Starting in从mongosh2.0.0:mongosh2.0.0开始:For boolean values in connection strings, you:对于连接字符串中的布尔值,您可以:must use必须使用trueorfalse.true或false。cannot use不能使用1,y,yes, ortinstead oftrue.1、y、yes或t代替true。cannot use不能使用-1,0,n,no, orfinstead offalse.-1、0、n、no或f代替false。