Docs HomeNode.js

Perform Bulk Operations执行批量操作

The bulkWrite() method performs batch write operations against a single collection. bulkWrite()方法对单个集合执行批处理写入操作。This method reduces the number of network round trips from your application to the server which therefore increases the throughput and performance. 这种方法减少了从应用程序到服务器的网络往返次数,从而提高了吞吐量和性能。Bulk writes return a collection of results for all operations only after all operations passed to the method complete.只有在传递给方法的所有操作完成后,大容量写入才会返回所有操作的结果集合。

You can specify one or more of the following write operations in bulkWrite():您可以在bulkWrite()中指定以下一个或多个写入操作:

  • insertOne
  • updateOne
  • updateMany
  • deleteOne
  • deleteMany
  • replaceOne

The bulkWrite() method accepts the following parameters:bulkWrite()方法接受以下参数:

  • operations: specifies the bulk write operations to perform. :指定要执行的大容量写入操作。Pass each operation to bulkWrite() as an object in an array. 将每个操作作为数组中的对象传递给bulkWrite()For examples that show the syntax for each write operation, see the bulkWrite API documentation.有关显示每个写入操作的语法的示例,请参阅bulkWrite API文档
  • options: optional可选。 settings that affect the execution of the operation, such as whether the write operations should execute in sequential order and the write concern.影响操作执行的设置,例如写入操作是否应按顺序执行以及写入问题。

    By default, MongoDB executes bulk write operations one-by-one in the specified order (i.e. serially). 默认情况下,MongoDB按照指定的顺序(即串行)逐个执行批量写入操作。During an ordered bulk write, if an error occurs during the processing of an operation, MongoDB returns without processing the remaining operations in the list. 在有序批量写入过程中,如果在处理操作过程中发生错误,MongoDB将返回,而不处理列表中的其余操作。In contrast, when ordered is false, MongoDB continues to process remaining write operations in the list. 相反,当orderedfalse时,MongoDB会继续处理列表中剩余的写操作。Unordered operations are theoretically faster since MongoDB can execute them in parallel, but should only be used if the writes do not depend on order.无序操作理论上更快,因为MongoDB可以并行执行它们,但只有在写入不依赖于顺序的情况下才应该使用。

If you create an index with a unique index constraint, you might encounter a duplicate key write error during an operation in the following format:如果创建具有唯一索引约束的索引,则在以下格式的操作过程中可能会遇到重复键写入错误:

Error during bulkWrite, BulkWriteError: E11000 duplicate key error collection: ...

Similarly, if you attempt to perform a bulk write against a collection that uses schema validation, you may encounter warnings or errors related to the formatting of inserted or modified documents.同样,如果尝试对使用架构验证的集合执行批量写入,则可能会遇到与插入或修改的文档的格式有关的警告或错误。

Example实例

The following code sample performs a bulk write operation on the theaters collection in the sample_mflix database. 以下代码示例对sample_mflix数据库中的theaters集合执行批量写入操作。The example call to bulkWrite() includes examples of insertOne, updateMany, and deleteOne write operations:bulkWrite()的示例调用包括insertOneupdateManydeleteOne写入操作的示例:

Note

You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. 您可以使用此示例连接到MongoDB的实例,并与包含示例数据的数据库进行交互。To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.要了解有关连接到MongoDB实例和加载示例数据集的更多信息,请参阅用法实例指南

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

// Replace the uri string with your MongoDB deployment's connection string.将uri字符串替换为MongoDB部署的连接字符串。
const uri = "<connection string uri>";

const client = new MongoClient(uri);

async function run() {
try {
const database = client.db("sample_mflix");
const theaters = database.collection("theaters");

const result = await theaters.bulkWrite([
{
insertOne: {
document: {
location: {
address: {
street1: "3 Main St.",
city: "Anchorage",
state: "AK",
zipcode: "99501",
},
},
},
},
},
{
insertOne: {
document: {
location: {
address: {
street1: "75 Penn Plaza",
city: "New York",
state: "NY",
zipcode: "10001",
},
},
},
},
},
{
updateMany: {
filter: { "location.address.zipcode": "44011" },
update: { $set: { is_in_ohio: true } },
upsert: true,
},
},
{
deleteOne: { filter: { "location.address.street1": "221b Baker St" } },
},
]);

console.log(result);
} finally {
await client.close();
}
}
run().catch(console.dir);

When you run the preceding example, you should see the following output:当您运行前面的示例时,您应该看到以下输出:

BulkWriteResult {
insertedCount: 2,
matchedCount: 1,
modifiedCount: 1,
deletedCount: 0,
upsertedCount: 0,
upsertedIds: {},
insertedIds: {
'0': new ObjectId("..."),
'1': new ObjectId("...")
}
}