Connection Guide连接指南¶
On this page
This guide shows you how to connect to a MongoDB instance or replica set deployment using the Node.js driver.本指南介绍如何使用Node.js驱动程序连接到MongoDB实例或副本集部署。
Connection URI连接URI¶
The connection URI is the set of instructions that the driver uses to connect to a MongoDB deployment. 连接URI是驱动程序用于连接MongoDB部署的一组指令。It instructs the driver on how it should connect to MongoDB and how it should behave while connected. 它指导驱动程序如何连接到MongoDB,以及连接时如何操作。The following example shows each part of the connection URI:以下示例显示了连接URI的每个部分:

In this example, for the protocol, we use 在本例中,对于协议,我们使用mongodb+srv
which specifies the DNS Seedlist Connection Format. mongodb+srv
,它指定DNS种子列表连接格式。This indicates that the hostname following it corresponds to the DNS SRV record of your MongoDB instance or deployment. 这表示它后面的主机名对应于MongoDB实例或部署的DNS SRV记录。If your instance or deployment does not have a DNS SRV record, use 如果您的实例或部署没有DNS SRV记录,请使用mongodb
to specify the Standard Connection Format.mongodb
指定标准连接格式。
If your deployment is on MongoDB Atlas, follow the Atlas driver connection guide to retrieve your connection string.如果部署在MongoDB Atlas上,请按照Atlas驱动程序连接指南检索连接字符串。
The next part of the connection string contains your username and password if you are using password-based authentication. 如果使用基于密码的身份验证,则连接字符串的下一部分包含用户名和密码。Replace the value of 将user
with your username and pass
with your password. user
的值替换为用户名,并使用密码传递。If you are using an authentication mechanism that does not require a username and password, omit this part of the connection URI.如果您使用的身份验证机制不需要用户名和密码,请省略连接URI的这一部分。
The next part of the connection string specifies the hostname or IP address and port of your MongoDB instance. 连接字符串的下一部分指定MongoDB实例的主机名或IP地址和端口。In the example above, we use 在上面的示例中,我们使用sample-hostname
as the hostname and 27017
as the port. sample-hostname
作为主机名,使用27017
作为端口。Replace these values to point to your MongoDB instance.替换这些值以指向您的MongoDB实例。
The last part of the connection string contains connection and authentication options as parameters. 连接字符串的最后一部分包含连接和身份验证选项作为参数。In the example above, we set two connection options:在上面的示例中,我们设置了两个连接选项:maxPoolSize=20
and w=majority
. maxPoolSize=20
和w=majority
。For more information on connection options, skip to the Connection Options section.有关连接选项的详细信息,请跳到“连接选项”部分。
The code below shows how you can use the sample connection URI in a client to connect to MongoDB.下面的代码显示了如何在客户端中使用示例连接URI连接到MongoDB。
const { MongoClient } = require("mongodb");
// Connection URI连接URI
const uri =
"mongodb+srv://sample-hostname:27017/?maxPoolSize=20&w=majority";
// Create a new MongoClient创建新的MongoClient
const client = new MongoClient(uri);
async function run(){
try {
// Connect the client to the server将客户端连接到服务器
await client.connect();
// Establish and verify connection建立并验证连接
await client.db("admin").command({ ping: 1 });
console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error确保完成/出错时客户端将关闭
await client.close();
}
}
run().catch(console.dir);
Other Ways to Connect to MongoDB连接MongoDB的其他方式¶
If you are connecting to a single MongoDB server instance or replica set that is not hosted on Atlas, see the following sections to find out how to connect.如果要连接到Atlas上未托管的单个MongoDB服务器实例或副本集,请参阅以下部分了解如何连接。
Connect to a MongoDB Server on Your Local Machine连接到本地计算机上的MongoDB服务器¶
If you need to run a MongoDB server on your local machine for development purposes instead of using an Atlas cluster, you need to complete the following:如果出于开发目的需要在本地计算机上运行MongoDB服务器,而不是使用Atlas群集,则需要完成以下操作:
Download the Community or Enterprise version of MongoDB Server.下载MongoDB服务器的社区版或企业版。Install and configure MongoDB Server.安装并配置MongoDB服务器。Start the server.启动服务器。
Always secure your MongoDB server from malicious attacks. 始终保护您的MongoDB服务器免受恶意攻击。See our Security Checklist for a list of security recommendations.有关安全建议的列表,请参阅我们的安全检查表。
After you successfully start your MongoDB server, specify your connection string in your driver connection code.成功启动MongoDB服务器后,请在驱动程序连接代码中指定连接字符串。
If your MongoDB Server is running locally, you can use the connection string 如果您的MongoDB服务器在本地运行,则可以使用连接字符串"mongodb://localhost:<port>"
where <port>
is the port number you configured your server to listen for incoming connections."mongodb://localhost:<port>"
其中<port>
是服务器配置为侦听传入连接的端口号。
If you need to specify a different hostname or IP address, see our Server Manual entry on Connection Strings.如果需要指定不同的主机名或IP地址,请参阅服务器手册上的连接字符串条目。
To test whether you can connect to your server, replace the connection string in the Connect to MongoDB Atlas code example and run it.要测试是否可以连接到服务器,请替换connect To MongoDB Atlas代码示例中的连接字符串并运行它。
Connect to a Replica Set连接到副本集¶
A MongoDB replica set deployment is a group of connected instances that store the same set of data. MongoDB副本集部署是存储同一组数据的一组连接实例。This configuration of instances provides data redundancy and high data availability.这种实例配置提供了数据冗余和高数据可用性。
To connect to a replica set deployment, specify the hostname and port numbers of each instance, separated by a comma, and the replica set name as the value of the 要连接到副本集部署,请指定每个实例的主机名和端口号(用逗号分隔),并将副本集名称指定为连接字符串中replicaSet
parameter in the connection string.replicaSet
参数的值。
mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myRs
When making a connection, the driver takes the following actions by default:建立连接时,默认情况下,驱动程序会执行以下操作:
Discovers all replica set members when given the address of any one member.在给定任何一个成员的地址时发现所有副本集成员。Dispatches operations to the appropriate member, such as write against the primary.将操作分派给适当的成员,例如针对主成员的写操作。
You only need to specify one host to connect to a replica set. 只需指定一台主机即可连接到副本集。However, to ensure connectivity if the specified host is unavailable, provide the full list of hosts.但是,如果指定的主机不可用,为确保连接,请提供完整的主机列表。
Direct Connection直接连接¶
To force your operations to run on the host specified in your connection URI, you can specify the 若要强制您的操作在连接URI中指定的主机上运行,您可以指定directConnection
connection option. directConnection
选项。If you specify this option, you must use the standard connection URI format. 如果指定此选项,则必须使用标准连接URI格式。The driver does not accept the DNS seedlist connection format (SRV) when you specify this option.指定此选项时,驱动程序不接受DNS种子列表连接格式(SRV)。
When you specify 指定directConnection
and connect to a secondary member of the replica set, your write operations fail because it is not the primary member. directConnection
并连接到副本集的辅助成员时,写入操作将失败,因为它不是主成员。To perform read operations, you must enable secondary reads. 要执行读取操作,必须启用辅助读取。See the read preference options for more information.有关详细信息,请参阅“读取首选项”。
Connection Options连接选项¶
This section explains several common MongoDB connection and authentication options. 本节介绍几种常见的MongoDB连接和身份验证选项。You can pass the connection options as parameters of the connection URI to specify the behavior of the client.您可以将连接选项作为连接URI的参数传递,以指定客户端的行为。
connectTimeoutMS
| integer
| 10000 | |
family
| number
| null | 4 , 6 , 0 , or null . The 0 and null settings attempt to connect with IPv6 and fall back to IPv4 upon failure.4 、6 、0 或null 。0 和null 设置尝试连接IPv6,并在失败时返回IPv4。 |
forceServerObjectId
| boolean
| false | _id values to documents instead of the driver._id 值分配给文档而不是驱动程序。 |
ignoreUndefined
| boolean
| false | |
keepAlive
| boolean
| true | keepAlive on the TCP socket. keepAlive 。 |
keepAliveInitialDelay
| integer
| 120000 | keepAlive on the TCP socket. keepAlive 之前等待的毫秒数。 |
logger
| object
| null | |
loggerLevel
| string
| null | error , warn , info , and debug .error 、warning 、info 和debug 。 |
maxPoolSize
| integer
| 100 | |
maxIdleTimeMS
| integer
| ∞ | |
minPoolSize
| integer
| 0 | |
noDelay
| boolean
| true | |
pkFactory
| object
| null | _id keys._id 键的主键工厂对象。 |
promiseLibrary
| object
| null | |
promoteBuffers
| boolean
| false | Buffer type data.Buffer 类型数据。 |
promoteLongs
| boolean
| true | Long values to a number if they fit inside 53 bits of resolution.Long 值在53位分辨率内,是否将其转换为数字。 |
promoteValues
| boolean
| true | false 时,它使用包装器类型来表示BSON值。 |
raw
| boolean
| false | |
serializeFunctions
| boolean
| false | |
serverApi
| string or enum
| null | |
socketTimeoutMS
| integer
| 360000 | |
tls
| boolean
| false | true when using a DNS seedlist (SRV) in the connection string. true 。false .false 来覆盖此行为。 |
validateOptions
| boolean
| false | false , the driver produces warnings only.false ,则驱动程序仅生成警告。 |
waitQueueTimeoutMS
| integer
| 0 | |
writeConcern
| string or integer
| null | |
directConnection
| boolean
| false |
For a complete list of options, see the MongoClient API reference page.有关选项的完整列表,请参阅MongoClient API参考页面。