mongodb

MongoDB Node.js Driver驱动程序

The official MongoDB driver for Node.js.官方的MongoDB for Node.js驱动程序。

Upgrading to version 7? Take a look at our upgrade guide here!升级到版本7?请在此处查看升级指南

Site站点 Link链接
Documentation文档 www.mongodb.com/docs/drivers/node
API DocsAPI文件 mongodb.github.io/node-mongodb-native
npm package www.npmjs.com/package/mongodb
MongoDB www.mongodb.com
MongoDB University大学 learn.mongodb.com
MongoDB Developer CenterMongoDB开发中心 www.mongodb.com/developer
Stack Overflow堆栈溢出 stackoverflow.com
Source Code源代码 github.com/mongodb/node-mongodb-native
Upgrade to v7升级到v7 etc/notes/CHANGES_7.0.0.md
Contributing贡献 CONTRIBUTING.md
Changelog更新日志 HISTORY.md

Releases are created automatically and signed using the Node team's GPG key. 发布是自动创建的,并使用节点团队的GPG键进行签名。This applies to the git tag as well as all release packages provided as part of a GitHub release. To verify the provided packages, download the key and import it using gpg:这适用于git标签以及作为GitHub发布的一部分提供的所有发布包。要验证提供的软件包,请下载键并使用gpg导入:

gpg --import node-driver.asc

The GitHub release contains a detached signature file for the NPM package (named mongodb-X.Y.Z.tgz.sig).GitHub版本包含NPM包的分离签名文件(名为mongodb-X.Y.Z.tgz.sig)。

The following command returns the link npm package.以下命令返回链接npm包。

npm view mongodb@vX.Y.Z dist.tarball

Using the result of the above command, a curl command can return the official npm package for the release.使用上述命令的结果,curl命令可以返回发布的官方npm包。

To verify the integrity of the downloaded package, run the following command:要验证下载包的完整性,请运行以下命令:

gpg --verify mongodb-X.Y.Z.tgz.sig mongodb-X.Y.Z.tgz

[!Note] No verification is done when using npm to install the package. The contents of the Github tarball and npm's tarball are identical.使用npm安装包时不进行验证。Github的tarball和npm的tarball的内容是相同的。

The MongoDB Node.js driver follows semantic versioning for its releases.MongoDB Node.js驱动程序的版本遵循语义版本控制。

Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a case in our issue management tool, JIRA:你觉得你发现了一个bug吗?想在node-mongodb-native中看到一个新功能吗?请在问题管理工具JIRA中打开一个案例:

Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the Core Server (i.e. SERVER) project are public.JIRA中所有驱动程序项目(即NODE、PYTHON、CSHARP、JAVA)和核心服务器(即Server)项目的Bug报告都是公开的

For issues with, questions about, or feedback for the Node.js driver, please look into our support channels. 有关Node.js驱动程序的问题、疑问或反馈,请查看支持渠道Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the MongoDB Community Forums.请不要直接向任何驱动程序开发人员发送问题或疑问的电子邮件,您更有可能在MongoDB社区论坛上得到答案。

Change history can be found in HISTORY.md.更改历史可以在HISTORY.md中找到。

The driver currently supports 4.2+ servers.该驱动程序目前支持4.2+服务器。

For exhaustive server and runtime version compatibility matrices, please refer to the following links:有关详尽的服务器和运行时版本兼容性矩阵,请参阅以下链接:

The following table describes add-on component version compatibility for the Node.js driver. Only packages with versions in these supported ranges are stable when used in combination.下表描述了Node.js驱动程序的附加组件版本兼容性。只有版本在这些支持范围内的软件包在组合使用时才是稳定的。

Component组件 mongodb@3.x mongodb@4.x mongodb@5.x mongodb@<6.12 mongodb@>=6.12 mongodb@7.x
bson ^1.0.0 ^4.0.0 ^5.0.0 ^6.0.0 ^6.0.0 ^7.0.0
bson-ext ^1.0.0 || ^2.0.0 ^4.0.0 N/A N/A N/A N/A
kerberos ^1.0.0 ^1.0.0 || ^2.0.0 ^1.0.0 || ^2.0.0 ^2.0.1 ^2.0.1 ^7.0.0
mongodb-client-encryption ^1.0.0 ^1.0.0 || ^2.0.0 ^2.3.0 ^6.0.0 ^6.0.0 ^7.0.0
mongodb-legacy N/A ^4.0.0 ^5.0.0 ^6.0.0 ^6.0.0 N/A
@mongodb-js/zstd N/A ^1.0.0 ^1.0.0 ^1.1.0 ^1.1.0 || ^2.0.0 ^7.0.0

We recommend using the latest version of typescript, however we currently ensure the driver's public types compile against typescript@5.6.0. 我们建议使用最新版本的typescript,但我们目前确保驱动程序的公共类型能够编译typescript@5.6.0This is the lowest typescript version guaranteed to work with our driver: older versions may or may not work - use at your own risk. 这是保证与驱动程序一起使用的最低typescript版本:旧版本可能有效,也可能无效——使用风险自负。Since typescript does not restrict breaking changes to major versions, we consider this support best effort. 由于typescript不限制对主要版本的破坏性更改,我们认为这是最好的支持。If you run into any unexpected compiler failures against our supported TypeScript versions, please let us know by filing an issue on our JIRA.如果您在我们支持的TypeScript版本上遇到任何意外的编译器故障,请在JIRA上提交问题,让我们知道。

Additionally, our Typescript types are compatible with the ECMAScript standard for our minimum supported Node version. Currently, our Typescript targets es2023.此外,Typescript类型与我们支持的最低Node版本的ECMAScript标准兼容。目前,打字目标是2023年。

The recommended way to get started using the Node.js driver is by using the npm (Node Package Manager) to install the dependency in your project.开始使用Node.js驱动程序的推荐方法是使用npm(节点包管理器)在项目中安装依赖项。

After you've created your own project using npm init, you can run:使用npm init创建自己的项目后,可以运行:

npm install mongodb

This will download the MongoDB driver and add a dependency entry in your package.json file.这将下载MongoDB驱动程序,并在package.json文件中添加一个依赖项。

If you are a Typescript user, you will need the Node.js type definitions to use the driver's definitions:如果你是Typescript用户,你需要Node.js类型定义来使用驱动程序的定义:

npm install -D @types/node

The MongoDB driver can optionally be enhanced by the following feature packages:MongoDB驱动程序可以通过以下功能包进行增强:

Maintained by MongoDB:由MongoDB维护:

Some of these packages include native C++ extensions. Consult the trouble shooting guide here if you run into compilation issues.其中一些包包含本机C++扩展。如果遇到编译问题,请参阅此处的故障排除指南

Third party:第三方:

This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the official documentation.本指南将向您展示如何使用Node.js和MongoDB设置一个简单的应用程序。它的范围只是如何设置驱动程序和执行简单的CRUD操作。有关更深入的报道,请参阅官方文档

First, create a directory where your application will live.首先,创建一个应用程序所在的目录。

mkdir myProject
cd myProject

Enter the following command and answer the questions to create the initial structure for your new project:输入以下命令并回答问题,为新项目创建初始结构:

npm init -y

Next, install the driver as a dependency.接下来,将驱动程序作为依赖项安装。

npm install mongodb

For complete MongoDB installation instructions, see the manual.有关完整的MongoDB安装说明,请参阅手册

  1. Download the right MongoDB version from MongoDB从MongoDB下载正确的MongoDB版本
  2. Create a database directory (in this case under /data).创建一个数据库目录(在本例中在/data下)。
  3. Install and start a mongod process.安装并启动mongod进程。
mongod --dbpath=/data

You should see the mongod process start up and print some status information.您应该看到mongod进程启动并打印一些状态信息。

Create a new app.js file and add the following code to try out some basic CRUD operations using the MongoDB driver.创建一个新的app.js文件,并添加以下代码,以尝试使用MongoDB驱动程序进行一些基本的CRUD操作。

Add code to connect to the server and the database myProject:添加代码以连接到服务器和数据库myProject

NOTE: Resolving DNS Connection issues解决DNS连接问题

Node.js 18 changed the default DNS resolution ordering from always prioritizing IPv4 to the ordering returned by the DNS provider. In some environments, this can result in localhost resolving to an IPv6 address instead of IPv4 and a consequent failure to connect to the server.Node.js 18将默认DNS解析顺序从始终优先考虑IPv4更改为DNS提供商返回的顺序。在某些环境中,这可能会导致localhost解析为IPv6地址而不是IPv4,从而导致无法连接到服务器。

This can be resolved by:这可以通过以下方式解决:

  • specifying the IP address family using the MongoClient family option (MongoClient(<uri>, { family: 4 } ))使用MongoClientfamily选项指定IP地址系列(MongoClient(<uri>, { family: 4 } )
  • launching mongod or mongos with the ipv6 flag enabled (--ipv6 mongod option documentation)在启用ipv6标志的情况下启动mongodmongos--ipv6 mongod选项文档)
  • using a host of 127.0.0.1 in place of localhost使用127.0.0.1的主机代替localhost
  • specifying the DNS resolution ordering with the --dns-resolution-order Node.js command line argument (e.g. node --dns-resolution-order=ipv4first)使用--dns-resolution-orderNode.js命令行参数指定DNS解析顺序(例如node --dns-resolution-order=ipv4first
const { MongoClient } = require('mongodb');
// or as an es module:或者作为es模块:
// import { MongoClient } from 'mongodb'

// Connection URL连接URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

// Database Name数据库名称
const dbName = 'myProject';

async function main() {
// Use connect method to connect to the server使用connect方法连接到服务器
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('documents');

// the following code examples can be pasted here...以下代码示例可以粘贴在这里…

return 'done.';
}

main()
.then(console.log)
.catch(console.error)
.finally(() => client.close());

Run your app from the command line with:使用以下命令行运行您的应用程序:

node app.js

The application should print Connected successfully to server to the console.应用程序应将“已成功连接到服务器”打印到控制台。

Add to app.js the following function which uses the insertMany method to add three documents to the documents collection.app.js中添加以下函数,该函数使用insertMany方法将三个文档添加到documents集合中。

const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]);
console.log('Inserted documents =>', insertResult);

The insertMany command returns an object with information about the insert operations.insertMany命令返回一个包含插入操作信息的对象。

Add a query that returns all the documents.添加一个返回所有文档的查询。

const findResult = await collection.find({}).toArray();
console.log('Found documents =>', findResult);

This query returns all the documents in the documents collection. If you add this below the insertMany example, you'll see the documents you've inserted.此查询返回documents集合中的所有文档。如果您在insertMany示例下方添加此项,您将看到您插入的文档。

Add a query filter to find only documents which meet the query criteria.添加查询筛选器,仅查找符合查询条件的文档。

const filteredDocs = await collection.find({ a: 3 }).toArray();
console.log('Found documents filtered by { a: 3 } =>', filteredDocs);

Only the documents which match 'a' : 3 should be returned.只应返回与'a' : 3匹配的文档。

The following operation updates a document in the documents collection.以下操作将更新documents集合中的文档。

const updateResult = await collection.updateOne({ a: 3 }, { $set: { b: 1 } });
console.log('Updated documents =>', updateResult);

The method updates the first document where the field a is equal to 3 by adding a new field b to the document set to 1. updateResult contains information about whether there was a matching document to update or not.该方法通过添加新字段b到文档并设置为1来更新字段a等于3的第一个文档。updateResult包含有关是否存在要更新的匹配文档的信息。

Remove the document where the field a is equal to 3.删除字段a等于3的文档。

const deleteResult = await collection.deleteMany({ a: 3 });
console.log('Deleted documents =>', deleteResult);

Indexes can improve your application's performance. The following function creates an index on the a field in the documents collection.索引可以提高应用程序的性能。以下函数在文档集合中的a字段上创建索引。

const indexName = await collection.createIndex({ a: 1 });
console.log('index name =', indexName);

For more detailed information, see the indexing strategies page.有关更多详细信息,请参阅索引策略页面。

If you need to filter certain errors from our driver, we have a helpful tree of errors described in etc/notes/errors.md.如果你需要从驱动程序中筛选某些错误,我们有一个有用的错误树,如etc/notes/errors.md所述。

It is our recommendation to use instanceof checks on errors and to avoid relying on parsing error.message and error.name strings in your code. We guarantee instanceof checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors.我们建议对错误使用instanceof检查,避免依赖于解析代码中的error.messageerror.name字符串。我们保证即时检查将根据semver指南通过,但错误可能会被细分,或者它们的消息可能会随时更改,甚至是补丁发布,因为我们认为这有助于提高错误的有用性。

Any new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release. This means instanceof will always be able to accurately capture the errors that our driver throws.我们添加到驱动程序中的任何新错误都将直接扩展现有的错误类,并且不会将现有的错误移动到主要版本之外的其他父类。这意味着instanceof将始终能够准确地捕获驱动程序抛出的错误。

const client = new MongoClient(url);
await client.connect();
const collection = client.db().collection('collection');

try {
await collection.insertOne({ _id: 1 });
await collection.insertOne({ _id: 1 }); // duplicate key error
} catch (error) {
if (error instanceof MongoServerError) {
console.log(`Error worth logging: ${error}`); // special case for some reason
}
throw error; // still want to crash
}

If you need to test with a change from the latest main branch, our mongodb npm package has nightly versions released under the nightly tag.如果你需要使用最新main分支的更改进行测试,mongodb npm包在nightly标签下发布了nightly版本。

npm install mongodb@nightly

Nightly versions are published regardless of testing outcome. This means there could be semantic breakages or partially implemented features. The nightly build is not suitable for production use.无论测试结果如何,都会发布夜间版本。这意味着可能存在语义断裂或部分实现的功能。夜间构建不适合生产使用。

Apache 2.0

© 2012-present MongoDB Contributors
© 2009-2012 Christian Amor Kvalheim