Docs Home / Node.js Driver / Connect

Create a 创建MongoClient

Overview概述

To connect to a MongoDB deployment, you need two things:要连接到MongoDB部署,您需要两件事:

  • Connection URI, also known as a connection string, which tells the Node.js driver which MongoDB deployment to connect to.连接URI,也被称为连接字符串,它告诉Node.js驱动程序连接哪个MongoDB部署。
  • MongoClient object, which creates the connection to and performs operations on the MongoDB deployment.MongoClient对象,创建与MongoDB部署的连接并对其执行操作。

You can also use MongoClientOptions to customize the way the Node.js driver behaves while connected to MongoDB.您还可以使用MongoClientOptions自定义Node.js驱动程序在连接到MongoDB时的行为方式。

This guide shows you how to create a connection string and use a MongoClient object to connect to MongoDB.本指南向您展示了如何创建连接字符串并使用MongoClient对象连接到MongoDB。

Connection URI连接URI

A standard connection string includes the following components:标准连接字符串包括以下组件:

Component组件Description描述
mongodb://Required. A prefix that identifies this as a string in the standard connection format.必需的。一个前缀,将其标识为标准连接格式中的字符串。
username:passwordOptional. Authentication credentials. If you include these, the client authenticates the user against the database specified in authSource. 可选。身份验证凭据。如果包含这些,客户端将根据authSource中指定的数据库对用户进行身份验证。For more information about the authSource connection option, see Verify the User Is in the Authentication Database in the Connection Troubleshooting guide.有关authSource连接选项的详细信息,请参阅《连接疑难解答》指南中的“验证用户是否在身份验证数据库中”
host[:port]Required. The host and optional port number where MongoDB is running. If you don't include the port number, the driver uses the default port, 27017.必需的。运行MongoDB的主机和可选端口号。如果不包括端口号,驱动程序将使用默认端口27017
/defaultauthdbOptional. The authentication database to use if the connection string includes username:password@ authentication credentials but not the authSource option. 可选。如果连接字符串包括username:password@身份验证凭据但不包括authSource选项,则使用的身份验证数据库。When you call client.db() with no argument, this is the database that is used. If you don't include this component, the client authenticates the user against the admin database.当您在没有参数的情况下调用client.db()时,这是使用的数据库。如果不包含此组件,客户端将根据管理员数据库对用户进行身份验证。
?<options>Optional. A query string that specifies connection-specific options as <name>=<value> pairs. See Specify Connection Options for a full description of these options.可选。一个查询字符串,将特定于连接的选项指定为<name>=<value>对。有关这些选项的完整说明,请参阅指定连接选项

For more information about creating a connection string, see Connection Strings in the MongoDB Server documentation.有关创建连接字符串的更多信息,请参阅MongoDB Server文档中的连接字符串

Atlas Connection ExampleAtlas连接示例

You must create a client to connect to a MongoDB deployment on Atlas. To create a client, construct an instance of MongoClient, passing in your URI and a MongoClientOptions object.您必须创建一个客户端才能连接到Atlas上的MongoDB部署。要创建客户端,请构造一个MongoClient实例,传入URI和MongoClientOptions对象。

Tip

Reuse Your Client重用您的客户端

As each MongoClient represents a pool of connections to the database, most applications only require a single instance of a MongoClient, even across multiple requests. 由于每个MongoClient代表一个到数据库的连接池,因此大多数应用程序只需要一个MongoClient实例,即使在多个请求之间也是如此。To learn more about how connection pools work in the driver, see the Connection Pools page.要了解有关连接池在驱动程序中如何工作的更多信息,请参阅连接池页面

Use the serverApi option in your MongoClientOptions object to enable the Stable API feature, which forces the server to run operations with behavior compatible with the specified API version.使用MongoClientOptions对象中的serverApi选项启用Stable API功能,该功能强一致性务器运行行为与指定API版本兼容的操作。

The following code shows how you can specify the connection string and the Stable API client option when connecting to a MongoDB deployment on Atlas and verify that the connection is successful:以下代码显示了如何在连接到Atlas上的MongoDB部署时指定连接字符串和Stable API客户端选项,并验证连接是否成功:

const { MongoClient, ServerApiVersion } = require("mongodb");

// Replace the placeholder with your Atlas connection string用Atlas连接字符串替换占位符
const uri = "<connection string>";

// Create a MongoClient with a MongoClientOptions object to set the Stable API version创建一个带有MongoClientOptions对象的MongoClient来设置Stable API版本
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
}
);

async function run() {
try {
// Connect the client to the server (optional starting in v4.7)将客户端连接到服务器(从v4.7开始可选)
await client.connect();

// Send a ping to confirm a successful connection发送ping确认连接成功
await client.db("admin").command({ ping: 1 });
console.log("Pinged your deployment. You successfully connected to MongoDB!");
} finally {
// Ensures that the client will close when you finish/error确保客户端在您完成/出错时关闭
await client.close();
}
}
run().catch(console.dir);

Note

The Node.js driver automatically calls the MongoClient.connect() method when using the client to perform CRUD operations on your MongoDB deployment. Call the MongoClient.connect() method explicitly if you want to verify that the connection is successful.当使用客户端对MongoDB部署执行CRUD操作时,Node.js驱动程序会自动调用MongoClient.connect()方法。如果要验证连接是否成功,请显式调用MongoClient.connect()方法。

Tip

Explicit Resource Management显式资源管理

The Node.js driver natively supports explicit resource management for MongoClient, ClientSession, ChangeStreams, and cursors. Node.js驱动程序原生支持MongoClientClientSessionChangeStreams和游标的显式资源管理。This feature is experimental and subject to change. To learn how to use explicit resource management, see the v6.9 Release Notes.此功能是实验性的,可能会发生变化。要了解如何使用显式资源管理,请参阅v6.9发行说明

To learn more about the Stable API feature, see the Stable API page.要了解有关Stable API功能的更多信息,请参阅Stable API页面

Prevent a Slow Operation From Delaying Other Operations防止慢速操作延迟其他操作

When you use the same MongoClient instance to run multiple MongoDB operations concurrently, a slow operation can cause delays to other operations. Slow operations keep a connection to MongoDB occupied, which can cause other operations to wait until another connection becomes available.当您使用同一个MongoClient实例同时运行多个MongoDB操作时,缓慢的操作可能会导致其他操作的延迟。慢速操作会占用与MongoDB的连接,这可能会导致其他操作等待另一个连接可用。

If you suspect that slow MongoDB operations are causing delays, you can check the performance of all in-progress operations by using the following methods:如果您怀疑缓慢的MongoDB操作会导致延迟,可以使用以下方法检查所有正在进行的操作的性能:

  • Enable the database profiler on your deployment. To learn more, see Database Profiler in the Server manual.在部署上启用数据库分析器。要了解更多信息,请参阅服务器手册中的数据库分析器
  • Run the db.currentOp() MongoDB Shell command. To learn more, see the db.currentOp() documentation in the Server manual.运行db.currentOp()MongoDB Shell命令。要了解更多信息,请参阅服务器手册中的db.currentOp()文档。
  • Enable connection pool monitoring. To learn more, see Connection Pool Events.启用连接池监视。要了解更多信息,请参阅连接池事件

After you determine which operations are causing delays, try to improve the performance of these operations. Read the Best Practices Guide for MongoDB Performance for possible solutions.在确定哪些操作导致延迟后,请尝试提高这些操作的性能。阅读MongoDB性能最佳实践指南,了解可能的解决方案。

If you implement performance best practices but still experience delays, you can modify your connection settings to increase the size of the connection pool. A connection pool is the group of connections to the server that the driver maintains at any time.如果您实施了性能最佳实践,但仍然遇到延迟,则可以修改连接设置以增加连接池的大小。连接池是驱动程序随时维护的与服务器的连接组。

To specify the maximum size of a connection pool, you can set the maxPoolSize option in the connection options for your MongoClient instance. 要指定连接池的最大大小,您可以在MongoClient实例的连接选项中设置maxPoolSize选项。The default value of maxPoolSize is 100. If the number of in-use connections to a server reaches maxPoolSize, the next operation sent to the server pauses until a connection to the driver becomes available. maxPoolSize的默认值为100。如果与服务器的正在使用的连接数达到maxPoolSize,则发送到服务器的下一个操作将暂停,直到与驱动程序的连接可用为止。The following code sets maxPoolSize to 150 when creating a new MongoClient:以下代码在创建新的MongoClient时将maxPoolSize设置为150

const client = new MongoClient(uri, { maxPoolSize: 150 });

Tip

To learn more about connection pooling, see the Connection Pool Overview section in the Connection Pools page.要了解有关连接池的更多信息,请参阅连接池页面中的连接池概述部分

API DocumentationAPI 文档

For more information about creating a MongoClient object with the Node.js driver, see the following API documentation:有关使用Node.js驱动程序创建MongoClient对象的更多信息,请参阅以下API文档: