mongodb

MongoDB Node.js DriverMongoDB Node.js驱动程序

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

Upgrading to version 6? Take a look at our upgrade guide here!是否升级到版本6?在这里查看升级指南

Quick Links

Site Link
Documentation www.mongodb.com/docs/drivers/node
API Docs mongodb.github.io/node-mongodb-native
npm package www.npmjs.com/package/mongodb
MongoDB www.mongodb.com
MongoDB University learn.mongodb.com
MongoDB Developer Center www.mongodb.com/developer
Stack Overflow stackoverflow.com
Source Code github.com/mongodb/node-mongodb-native
Upgrade to v6 etc/notes/CHANGES_6.0.0.md
Contributing CONTRIBUTING.md
Changelog HISTORY.md history.html

Bugs / Feature Requests

Think you’ve found a bug? 你觉得你发现了一个bug吗?Want to see a new feature in node-mongodb-native? 想在node-mongodb-native中看到一个新功能吗?Please open a case in our issue management tool, JIRA:请在问题管理工具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)项目的错误报告都是public

Support / Feedback

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 Log

Change history can be found in HISTORY.md history.html.

Compatibility

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

Component Support Matrix

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

Component组成部分 mongodb@3.x mongodb@4.x mongodb@5.x mongodb@6.x
bson ^1.0.0 ^4.0.0 ^5.0.0 ^6.0.0
bson-ext ^1.0.0 || ^2.0.0 ^4.0.0 N/A N/A
kerberos ^1.0.0 ^1.0.0 || ^2.0.0 ^1.0.0 || ^2.0.0 ^2.0.1
mongodb-client-encryption ^1.0.0 ^1.0.0 || ^2.0.0 ^2.3.0 ^6.0.0
mongodb-legacy N/A ^4.0.0 ^5.0.0 ^6.0.0
@mongodb-js/zstd N/A ^1.0.0 ^1.0.0 ^1.1.0

Typescript Version

We recommend using the latest version of typescript, however we currently ensure the driver's public types compile against typescript@4.1.6. 我们建议使用最新版本的typescript,但我们目前确保驱动程序的公共类型根据typescript@4.1.6This 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上提交问题,告知我们。

Installation安装

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

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

npm install mongodb
# or ...
yarn add 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

Driver Extensions驱动程序扩展

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.其中一些包包含本机C++扩展。 Consult the trouble shooting guide here if you run into compilation issues.如果遇到编译问题,请参阅此处的故障排除指南

Third party:第三方:

Quick Start快速入门

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

Create the package.json file创建package.json文件

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

Start a MongoDB Server启动MongoDB服务器

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

  1. Download the right MongoDB version from MongoDBMongoDB下载正确的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进程启动并打印一些状态信息。

Connect to MongoDB连接到MongoDB

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. Node.js 18将默认的DNS解析顺序从始终优先ipv4更改为DNS提供商返回的顺序。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.在某些环境中,这可能导致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:
// import { MongoClient } from 'mongodb'

// Connection 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
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.应用程序应将Connected to server successfully打印到控制台。

Insert a Document插入文档

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

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命令返回一个对象,其中包含有关插入操作的信息。

Find All Documents查找所有文档

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. 此查询返回documents集合中的所有文档。If you add this below the insertMany example you'll see the document's you've inserted.如果你在insertMany下面添加这个,你会看到你插入的文档。

Find Documents with a Query Filter使用查询筛选器查找文档

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匹配的文档。

Update a document更新文档

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的文档添加新字段b来更新字段a等于3的第一文档。updateResult包含有关是否存在要更新的匹配文档的信息。

Remove a document删除文档

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);

Index a Collection为集合编制索引

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

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

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

Error Handling错误处理

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字符串。我们保证instanceof检查将根据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
}

Nightly releases夜间发布

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 sematic breakages or partially implemented features. The nightly build is not suitable for production use.这意味着可能存在信号中断或部分实现的功能。夜间建造不适合生产使用。

Next Steps下一步

License

Apache 2.0

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

Generated using TypeDoc