Database Manual / Reference / mongosh Methods / Connections

connect() (mongosh method方法)

Description描述

connect(url, user, password)

Creates a connection to a MongoDB instance and returns the reference to the database. 创建到MongoDB实例的连接,并返回对数据库的引用。However, in most cases, use the Mongo() object and its getDB() method instead.但是,在大多数情况下,请使用Mongo()对象及其getDB()方法。

Parameter参数Type类型Description描述
urlstring字符串

Specifies the connection string. You can specify either:指定连接字符串。您可以指定以下任一值:

  • <hostname>:<port>/<database>
  • <hostname>/<database>
  • <database>
userstring字符串Optional. 可选。Specifies an existing username with access privileges for this database. If user is specified, you must include the password parameter as well.指定具有此数据库访问权限的现有用户名。如果指定了用户,则还必须包含密码参数。
passwordstring字符串Optional 可选。unless the user parameter is specified. Specifies the password for the user.除非指定了user参数。指定user的密码。

Compatibility兼容性

This method is available in deployments hosted in the following environments:此方法在以下环境中托管的部署中可用:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Example示例

The following example instantiates a new connection to the MongoDB instance running on the localhost interface and returns a reference to myDatabase:以下示例实例化到在localhost接口上运行的MongoDB实例的新连接,并返回对myDatabase的引用:

db = connect("localhost:27017/myDatabase")