Docs Home / Node.js Driver

Bulk Operations批量操作

Overview概述

In this guide, you can learn how to use the Node.js driver to perform bulk operations. Bulk operations help reduce the number of calls to the server. Instead of sending a request for each operation, you can perform multiple operations within one action.在本指南中,您可以学习如何使用Node.js驱动程序执行批量操作。批量操作有助于减少对服务器的调用次数。您可以在一个操作中执行多个操作,而不是为每个操作发送请求。

Tip

To learn more about bulk operations, see Bulk Write Operations in the MongoDB Server manual.要了解有关批量操作的更多信息,请参阅MongoDB服务器手册中的批量写入操作

You can use bulk operations to perform multiple write operations on a collection. You can also run bulk operations from the client, which allows you to perform bulk writes across multiple namespaces. In MongoDB, a namespace consists of the database name and the collection name in the format <database>.<collection>.您可以使用批量操作对集合执行多个写入操作。您还可以从客户端运行批量操作,这允许您跨多个命名空间执行批量写入。在MongoDB中,命名空间由数据库名称和集合名称组成,格式为<database>.<collection>

This guide includes the following sections:本指南包括以下部分:

  • Bulk Insert Operations批量插入操作 describes how to perform bulk insert operations on your collection or client.描述如何在集合或客户端上执行批量插入操作。
  • Bulk Replace Operations批量更换操作 describes how to perform bulk replace operations on your collection or client.描述如何在集合或客户端上执行批量替换操作。
  • Bulk Update Operations批量更新操作 describes how to perform bulk update operations on your collection or client.描述如何在集合或客户端上执行批量更新操作。
  • Bulk Delete Operations批量删除操作 describes how to perform bulk delete operations on your collection or client.描述如何在集合或客户端上执行批量删除操作。
  • Return Type返回类型 describes the return object that results from your bulk write operations.描述了批量写入操作产生的返回对象。
  • Handling Exceptions处理异常 describes the exceptions that occur if any of the operations in a bulk write operation fail.描述了在批量写入操作中的任何操作失败时发生的异常。
  • Additional Information附加信息 provides links to resources and API documentation for types and methods mentioned in this guide.提供了指向本指南中提到的类型和方法的资源和API文档的链接。

Important

Server and Driver Version Requirements服务器和驱动程序版本要求

Collection-level bulk write operations require the following versions:集合级批量写入操作需要以下版本:

  • MongoDB Server version 3.2 or laterMongoDB服务器版本3.2或更高版本
  • Node.js driver version 3.6 or laterNode.js驱动程序3.6或更高版本

Client-level bulk write operations require the following versions:客户端级批量写入操作需要以下版本:

  • MongoDB Server version 8.0 or laterMongoDB服务器8.0或更高版本
  • Node.js driver version 6.10 or laterNode.js驱动程序版本6.10或更高版本

Sample Data样本数据

The examples in this guide use the movies and users collections in the sample_mflix database, which is included in the Atlas sample datasets. 本指南中的示例使用了Atlas示例数据集中包含的sample_mflix数据库中的moviesusers集合。To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.要了解如何创建免费的MongoDB Atlas集群并加载示例数据集,请参阅MongoDB入门指南

Bulk Insert Operations批量插入操作

To perform a bulk insert operation, create a bulk operation model for each document you want to insert. Then, pass a list of these models to the bulkWrite() method.要执行批量插入操作,请为要插入的每个文档创建批量操作模型。然后,将这些模型的列表传递给bulkWrite()方法。

This section describes how to perform the following types of bulk operations:本节介绍如何执行以下类型的批量操作:

Collection Bulk Inserts集合批量插入

To perform a bulk insert operation on your collection, create an InsertOneModel for each operation. Then, call the bulkWrite() method on your collection and pass an array of models as a parameter. 要对集合执行批量插入操作,请为每个操作创建InsertOneModel。然后,在你的集合上调用bulkWrite()方法,并传递一个模型数组作为参数。To create an InsertOneModel, specify the model's document field and set it to the document you want to insert.要创建InsertOneModel,请指定模型的document字段并将其设置为要插入的文档。

Example示例

This example performs the following actions:此示例执行以下操作:

  1. Specifies two InsertOneModel instances in an array. Each InsertOneModel represents a document to insert into the movies collection in the sample_mflix database.在数组中指定两个InsertOneModel实例。每个InsertOneModel代表一个要插入到sample_mflix数据库中的movies集合中的文档。
  2. Calls the bulkWrite() method on the movies collection and passes an array of models as a parameter.调用movies集合上的bulkWrite()方法,并将模型数组作为参数传递。
  3. Prints the number of inserted documents.打印插入文档的数量。
const insertModels = [{
insertOne: {
document: {
title: "The Favourite",
year: 2018,
rated: "R",
released: "2018-12-21"
}
}
}, {
insertOne: {
document: {
title: "I, Tonya",
year: 2017,
rated: "R",
released: "2017-12-08"
}
}
}];

const insertResult = await movies.bulkWrite(insertModels);
console.log(`Inserted documents: ${insertResult.insertedCount}`);
Inserted documents: 2

Client Bulk Inserts客户端批量插入

To perform a bulk insert operation across multiple collections or databases, create a ClientBulkWriteModel for each operation. Then, call the bulkWrite() method on your client and pass an array of models as a parameter.要跨多个集合或数据库执行批量插入操作,请为每个操作创建ClientBulkWriteModel。然后,在客户端调用bulkWrite()方法,并传递一个模型数组作为参数。

The following table describes the fields that you can set in a ClientBulkWriteModel to specify an insert operation:下表描述了可以在ClientBulkWriteModel中设置以指定插入操作的字段:

Field字段Description描述
namespaceThe namespace in which to insert a document.插入文档的命名空间。
Type: 类型:String
nameThe operation you want to perform. For insert operations, set this field to "insertOne".您要执行的操作。对于插入操作,请将此字段设置为"insertOne"
Type: 类型:String
documentThe document to insert.要插入的文档。
Type: 类型:Document

Example示例

This example performs the following actions:此示例执行以下操作:

  1. Specifies three ClientBulkWriteModel instances in an array. The first two models represent documents to insert into the movies collection, and the last model represents a document to insert into the users collection.在数组中指定三个ClientBulkWriteModel实例。前两个模型表示要插入movies集合的文档,最后一个模型表示需要插入users集合的文档。
  2. Calls the bulkWrite() method on a client and passes an array of models as a parameter.在客户端调用bulkWrite()方法,并将模型数组作为参数传递。
  3. Prints the number of inserted documents.打印插入文档的数量。
const clientInserts = [{
namespace: "sample_mflix.movies",
name: "insertOne",
document: {
title: "The Favourite",
year: 2018,
rated: "R",
released: "2018-12-21"
}
}, {
namespace: "sample_mflix.movies",
name: "insertOne",
document: {
title: "I, Tonya",
year: 2017,
rated: "R",
released: "2017-12-08"
}
}, {
namespace: "sample_mflix.users",
name: "insertOne",
document: {
name: "Brian Schwartz",
email: "bschwartz@example.com"
}
}];

const clientInsertRes = await client.bulkWrite(clientInserts);
console.log(`Inserted documents: ${clientInsertRes.insertedCount}`);
Inserted documents: 3

Bulk Replace Operations批量更换操作

To perform a bulk replace operation, create a bulk operation model for each document you want to replace. Then, pass a list of these models to the bulkWrite() method.要执行批量替换操作,请为要替换的每个文档创建批量操作模型。然后,将这些模型的列表传递给bulkWrite()方法。

This section describes how to perform the following types of bulk operations:本节介绍如何执行以下类型的批量操作:

Collection Bulk Replacements集合批量替换

To perform a bulk replace operation on your collection, create a ReplaceOneModel for each operation. Then, call the bulkWrite() method on your collection and pass an array of models as a parameter.要对集合执行批量替换操作,请为每个操作创建一个ReplaceOneModel。然后,在你的集合上调用bulkWrite()方法,并传递一个模型数组作为参数。

The following table describes the fields that you can set in a ReplaceOneModel:下表描述了可以在ReplaceOneModel中设置的字段:

Field字段Description描述
filterThe filter that matches the document you want to replace.与要替换的文档匹配的筛选器。
Type: 类型:Document
replacementThe replacement document.替换文件。
Type: 类型:Document
collation(Optional) The collation to use when sorting results. To learn more about collations, see the Collation section of the Configure CRUD Operations guide.(可选)排序结果时使用的排序规则。要了解有关排序规则的更多信息,请参阅《配置CRUD操作》指南的“排序规则”部分。
Type: 类型:String or Object
hint(Optional) The index to use for the operation. To learn more about indexes, see the Indexes for Query Optimization guide.(可选)用于操作的索引。要了解有关索引的更多信息,请参阅《查询优化索引》指南。
Type: 类型:Bson
upsert(Optional) Whether a new document is created if no document matches the filter.(可选)如果没有与筛选器匹配的文档,是否创建新文档。
By default, this field is set to false.默认情况下,此字段设置为false
Type: 类型:Boolean

Example示例

This example performs the following actions:此示例执行以下操作:

  1. Specifies two ReplaceOneModel instances in an array. The ReplaceOneModel instances contain instructions to replace documents representing movies in the movies collection.在数组中指定两个ReplaceOneModel实例。ReplaceOneModel实例包含替换电影集合中代表movies的文档的说明。
  2. Calls the bulkWrite() method on the movies collection and passes an array of models as a parameter.调用movies集合上的bulkWrite()方法,并将模型数组作为参数传递。
  3. Prints the number of modified documents.打印已修改文档的数量。
const replaceOperations = [{
replaceOne: {
filter: {
title: "The Dark Knight"
},
replacement: {
title: "The Dark Knight Rises",
year: 2012,
rating: "PG-13"
},
upsert: false
}
}, {
replaceOne: {
filter: {
title: "Inception"
},
replacement: {
title: "Inception Reloaded",
year: 2010,
rating: "PG-13"
},
upsert: false
}
}];

const replaceResult = await movies.bulkWrite(replaceOperations);
console.log(`Modified documents: ${replaceResult.modifiedCount}`);
Modified documents: 2

Client Bulk Replacements客户端批量替换

To perform a bulk replace operation across multiple collections or databases, create a ClientBulkWriteModel for each operation. Then, call the bulkWrite() method on your client and pass an array of models as a parameter.要跨多个集合或数据库执行批量替换操作,请为每个操作创建ClientBulkWriteModel。然后,在客户端调用bulkWrite()方法,并传递一个模型数组作为参数。

The following table describes the fields that you can set in a ClientBulkWriteModel to specify a replace operation:下表描述了可以在ClientBulkWriteModel中设置以指定替换操作的字段:

Field字段Description描述
namespaceThe namespace in which to replace a document.替换文档的命名空间。
Type: 类型:String
nameThe operation you want to perform. For replace operations, set this field to "replaceOne".您要执行的操作。对于替换操作,请将此字段设置为"replaceOne"
Type: 类型:String
filterThe filter that matches the document you want to replace.与要替换的文档匹配的筛选器。
Type: 类型:Document
replacementThe replacement document.替换文件。
Type: 类型:Document
collation(Optional) The collation to use when sorting results. To learn more about collations, see the Collation section of the Configure CRUD Operations guide.(可选)排序结果时使用的排序规则。要了解有关排序规则的更多信息,请参阅《配置CRUD操作》指南的“排序规则”部分。
Type: 类型:String or Object
hint(Optional) The index to use for the operation. To learn more about indexes, see the Indexes for Query Optimization guide.(可选)用于操作的索引。要了解有关索引的更多信息,请参阅《查询优化索引》指南。
Type: 类型:Bson

Example示例

This example performs the following actions:此示例执行以下操作:

  1. Specifies three ClientBulkWriteModel instances in an array. The first two models contain replacement instructions for documents in the movies collection, and the last model contains replacement instructions for a document in the users collection.在数组中指定三个ClientBulkWriteModel实例。前两个模型包含movies集合中的文档的替换说明,最后一个模型包含users集合中的文件的替换说明。
  2. Calls the bulkWrite() method on a client and passes an array of models as a parameter.在客户端调用bulkWrite()方法,并将模型数组作为参数传递。
  3. Prints the number of modified documents.打印已修改文档的数量。
const clientReplacements = [{
namespace: "sample_mflix.movies",
name: "replaceOne",
filter: {
title: "The Dark Knight"
},
replacement: {
title: "The Dark Knight Rises",
year: 2012,
rating: "PG-13"
}
}, {
namespace: "sample_mflix.movies",
name: "replaceOne",
filter: {
title: "Inception"
},
replacement: {
title: "Inception Reloaded",
year: 2010,
rating: "PG-13"
}
}, {
namespace: "sample_mflix.users",
name: "replaceOne",
filter: {
name: "April Cole"
},
replacement: {
name: "April Franklin",
email: "aprilfrank@example.com"
}
}];

const clientReplaceRes = await client.bulkWrite(clientReplacements);
console.log(`Modified documents: ${clientReplaceRes.modifiedCount}`);
Modified documents: 3

Bulk Update Operations批量更新操作

To perform a bulk update operation, create a bulk operation model for each update you want to make. Then, pass a list of these models to the bulkWrite() method.要执行批量更新操作,请为要进行的每个更新创建批量操作模型。然后,将这些模型的列表传递给bulkWrite()方法。

This section describes how to perform the following types of bulk operations:本节介绍如何执行以下类型的批量操作:

Collection Bulk Updates集合批量更新

To perform a bulk update operation on your collection, create an UpdateOneModel or UpdateManyModel for each operation. Then, call the bulkWrite() method on your collection and pass an array of models as a parameter. 要对集合执行批量更新操作,请为每个操作创建UpdateOneModelUpdateManyModel。然后,在你的集合上调用bulkWrite()方法,并传递一个模型数组作为参数。An UpdateOneModel updates only one document that matches a filter, while an UpdateManyModel updates all documents that match a filter.UpdateOneModel只更新一个与筛选器匹配的文档,而UpdateManyModel则更新所有与筛选器相匹配的文档。

The following table describes the fields you can set in an UpdateOneModel or UpdateManyModel:下表描述了可以在UpdateOneModelUpdateManyModel中设置的字段:

Field字段Description描述
filterThe filter that matches one or more documents you want to update. When specified in an UpdateOneModel, only the first matching document will be updated. When specified in an UpdateManyModel, all matching documents will be updated.与要更新的一个或多个文档匹配的筛选器。在UpdateOneModel中指定时,只会更新第一个匹配的文档。当在UpdateManyModel中指定时,所有匹配的文档都将被更新。
Type: 类型:Document
updateThe update to perform.要执行的更新。
Type: 类型:Document
arrayFilters(Optional) A set of filters specifying which array elements an update applies to if you are updating an array-valued field.(可选)一组筛选器,指定在更新数组值字段时更新应用于哪些数组元素。
Type: 类型:Array
collation(Optional) The collation to use when sorting results. To learn more about collations, see the Collation section of the Configure CRUD Operations guide.(可选)排序结果时使用的排序规则。要了解有关排序规则的更多信息,请参阅《配置CRUD操作》指南的“排序规则”部分。
Type: 类型:Object
hint(Optional) The index to use for the operation. To learn more about indexes, see the Indexes for Query Optimization guide.(可选)用于操作的索引。要了解有关索引的更多信息,请参阅《查询优化索引》指南。
Type: 类型:String or Object
upsert(Optional) Whether a new document is created if no document matches the filter. By default, this field is set to false.(可选)如果没有与筛选器匹配的文档,是否创建新文档。默认情况下,此字段设置为false
Type: 类型:Boolean

Example示例

This example performs the following actions:此示例执行以下操作:

  1. Specifies an UpdateOneModel and an UpdateManyModel instance in an array. These models contain instructions to update documents representing movies in the movies collection.在数组中指定UpdateOneModelUpdateManyModel实例。这些模型包含更新代表电影集合中电影的文档的说明。
  2. Calls the bulkWrite() method on the movies collection and passes an array of models as a parameter.调用movies集合上的bulkWrite()方法,并将模型数组作为参数传递。
  3. Prints the number of modified documents.打印已修改文档的数量。
const updateOperations = [{
updateOne: {
filter: {
title: "Interstellar"
},
update: {
$set: {
title: "Interstellar Updated",
genre: "Sci-Fi Adventure"
}
},
upsert: true
}
}, {
updateMany: {
filter: {
rated: "PG-13"
},
update: {
$set: {
rated: "PG-13 Updated",
genre: "Updated Genre"
}
}
}
}];

const updateResult = await movies.bulkWrite(updateOperations);
console.log(`Modified documents: ${updateResult.modifiedCount}`);
Modified documents: 2320

Client Bulk Updates客户端批量更新

To perform a bulk update operation across multiple collections or databases, create a ClientBulkWriteModel for each operation. Then, call the bulkWrite() method on your client and pass an array of models as a parameter.要跨多个集合或数据库执行批量更新操作,请为每个操作创建ClientBulkWriteModel。然后,在客户端调用bulkWrite()方法,并传递一个模型数组作为参数。

The following table describes the fields you can set in a ClientBulkWriteModel to specify an update operation:下表描述了可以在ClientBulkWriteModel中设置以指定更新操作的字段:

Field字段Description描述
namespaceThe namespace in which to update a document.用于更新文档的命名空间。
Type: 类型:String
nameThe operation you want to perform. For update operations, set this field to "updateOne" or "updateMany".您要执行的操作。对于更新操作,请将此字段设置为"updateOne""updateMany"
Type: 类型:String
filterThe filter that matches one or more documents you want to update. If you set the model name to "updateOne", only the first matching document is updated. 与要更新的一个或多个文档匹配的筛选器。如果将模型name设置为"updateOne",则仅更新第一个匹配的文档。If you set name to "updateMany", all matching documents are updated.如果将name设置为"updateMany",则所有匹配的文档都会更新。
Type: 类型:Document
updateThe updates to perform.要执行的更新。
Type: 类型:Document or Document[]
arrayFilters(Optional) A set of filters specifying which array elements an update applies to if you are updating an array-valued field.(可选)一组筛选器,指定在更新数组值字段时更新应用于哪些数组元素。
Type: 类型:Document[]
collation(Optional) The collation to use when sorting results. To learn more about collations, see the Collation section of the Configure CRUD Operations guide.(可选)排序结果时使用的排序规则。要了解有关排序规则的更多信息,请参阅《配置CRUD操作》指南的“排序规则”部分。
Type: 类型:Document
hint(Optional) The index to use for the operation. To learn more about indexes, see the Indexes for Query Optimization guide.(可选)用于操作的索引。要了解有关索引的更多信息,请参阅《查询优化索引》指南。
Type: 类型:Document or String
upsert(Optional) Whether a new document is created if no document matches the filter. By default, this field is set to false.(可选)如果没有与筛选器匹配的文档,是否创建新文档。默认情况下,此字段设置为false
Type: 类型:Boolean

Example示例

This example performs the following actions:此示例执行以下操作:

  1. Specifies two ClientBulkWriteModel instances in an array. The first model specifies an update many operation on the movies collection, and the second model specifies an update one operation on the users collection.在数组中指定两个ClientBulkWriteModel实例。第一个模型指定了对movies集合的更新多次操作,第二个模型指定对users集合的更新一次操作。
  2. Calls the bulkWrite() method on a client and passes an array of models as a parameter.在客户端调用bulkWrite()方法,并将模型数组作为参数传递。
  3. Prints the number of modified documents.打印已修改文档的数量。
const clientUpdates = [{
namespace: "sample_mflix.movies",
name: "updateMany",
filter: {
rated: "PG-13"
},
update: {
$set: {
rated: "PG-13 Updated",
genre: "Updated Genre"
}
},
upsert: false
}, {
namespace: "sample_mflix.users",
name: "updateOne",
filter: {
name: "Jon Snow"
},
update: {
$set: {
name: "Aegon Targaryen",
email: "targaryen@example.com"
}
},
upsert: false
}];
const clientUpdateRes = await client.bulkWrite(clientUpdates);
console.log(`Modified documents: ${clientUpdateRes.modifiedCount}`);
Modified documents: 2320

Bulk Delete Operations批量删除操作

To perform a bulk delete operation, create a bulk operation model for each delete operation. Then, pass a list of these models to the bulkWrite() method.要执行批量删除操作,请为每个删除操作创建批量操作模型。然后,将这些模型的列表传递给bulkWrite()方法。

This section describes how to perform the following types of bulk operations:本节介绍如何执行以下类型的批量操作:

Collection Bulk Deletes批量删除集合

To perform a bulk delete operation on your collection, create a DeleteOneModel or DeleteManyModel for each operation. 要对集合执行批量删除操作,请为每个操作创建DeleteOneModelDeleteManyModelThen, call the bulkWrite() method on your collection and pass an array of models as a parameter. 然后,在你的集合上调用bulkWrite()方法,并传递一个模型数组作为参数。A DeleteOneModel deletes only one document that matches a filter, while a DeleteManyModel deletes all documents that match a filter.DeleteOneModel仅删除一个与筛选器匹配的文档,而DeleteManyModel则删除所有与筛选器相匹配的文档。

The following table describes the fields you can set in a DeleteOneModel or DeleteManyModel:下表描述了可以在DeleteOneModelDeleteManyModel中设置的字段:

Field字段Description描述
filterThe filter that matches one or more documents you want to delete. When specified in a DeleteOneModel, only the first matching document will be deleted. 与要删除的一个或多个文档匹配的筛选器。在DeleteOneModel中指定时,只会删除第一个匹配的文档。When specified in a DeleteManyModel, all matching documents will be deleted.DeleteManyModel中指定时,所有匹配的文档都将被删除。
Type: 类型:Document
collation(Optional) The collation to use when sorting results. To learn more about collations, see the Collation section of the Configure CRUD Operations guide.(可选)排序结果时使用的排序规则。要了解有关排序规则的更多信息,请参阅《配置CRUD操作》指南的“排序规则”部分。
Type: 类型:Object
hint(Optional) The index to use for the operation. To learn more about indexes, see the Indexes for Query Optimization guide.(可选)用于操作的索引。要了解有关索引的更多信息,请参阅《查询优化索引》指南。
Type: 类型:String or Object

Example示例

This example performs the following actions:此示例执行以下操作:

  1. Specifies a DeleteOneModel and a DeleteManyModel instance in an array. These models contain instructions to delete documents in the movies collection.在数组中指定DeleteOneModelDeleteManyModel实例。这些模型包含删除电影集合中文档的说明。
  2. Calls the bulkWrite() method on the movies collection and passes an array of models as a parameter.调用movies集合上的bulkWrite()方法,并将模型数组作为参数传递。
  3. Prints the number of deleted documents.打印已删除文档的数量。
const deleteOperations = [{
deleteOne: {
filter: {
title: "Dunkirk"
}
}
}, {
deleteMany: {
filter: {
rated: "R"
}
}
}];

const deleteResult = await movies.bulkWrite(deleteOperations);
console.log(`Deleted documents: ${deleteResult.deletedCount}`);
Deleted documents: 5538

Client Bulk Deletes客户端批量删除

To perform a bulk delete operation across multiple collections or databases, create a ClientBulkWriteModel for each operation. Then, call the bulkWrite() method on your client and pass an array of models as a parameter.要跨多个集合或数据库执行批量删除操作,请为每个操作创建ClientBulkWriteModel。然后,在客户端调用bulkWrite()方法,并传递一个模型数组作为参数。

The following table describes the fields you can set in a ClientBulkWriteModel to specify a delete operation:下表描述了可以在ClientBulkWriteModel中设置的字段,以指定删除操作:

Field字段Description描述
namespaceThe namespace in which to delete a document.用于删除文档的命名空间。
Type: 类型:String
nameThe operation you want to perform. For delete operations, set this field to "deleteOne" or "deleteMany".您要执行的操作。对于删除操作,请将此字段设置为"deleteOne""deleteMany"
Type: 类型:String
filterThe filter that matches one or more documents you want to delete. 与要删除的一个或多个文档匹配的筛选器。If you set the model name to "deleteOne", only the first matching document is deleted. If you set name to "deleteMany", all matching documents are deleted.如果将模型name设置为"deleteOne",则只会删除第一个匹配的文档。如果将name设置为"deleteMany",则所有匹配的文档都将被删除。
Type: 类型:Document
hint(Optional) The index to use for the operation. To learn more about indexes, see the Indexes for Query Optimization guide.(可选)用于操作的索引。要了解有关索引的更多信息,请参阅《查询优化索引》指南。
Type: 类型:Document or String
collation(Optional) The collation to use when sorting results. To learn more about collations, see the Collation section of the Configure CRUD Operations guide.(可选)排序结果时使用的排序规则。要了解有关排序规则的更多信息,请参阅《配置CRUD操作》指南的“排序规则”部分。
Type: 类型:Document

Example示例

This example performs the following actions:此示例执行以下操作:

  1. Specifies two ClientBulkWriteModel instances in an array. The first model specifies a delete many operation on the movies collection, and the second model specifies a delete one operation on the users collection.在数组中指定两个ClientBulkWriteModel实例。第一个模型指定了对movies集合的删除多个操作,第二个模型指定对users集合的删除一个操作。
  2. Calls the bulkWrite() method on a client and passes an array of models as a parameter.在客户端调用bulkWrite()方法,并将模型数组作为参数传递。
  3. Prints the number of modified documents.打印已修改文档的数量。
const clientDeletes = [{
namespace: "sample_mflix.movies",
name: "deleteMany",
filter: {
rated: "R"
}
}, {
namespace: "sample_mflix.users",
name: "deleteOne",
filter: {
email: "emilia_clarke@gameofthron.es"
}
}];

const clientDeleteRes = await client.bulkWrite(clientDeletes);
console.log(`Deleted documents: ${clientDeleteRes.deletedCount}`);
Deleted documents: 5538

Return Type返回类型

BulkWriteResult

The Collection.bulkWrite() method returns a BulkWriteResult object, which provides information about your bulk operation.Collection.bulkWrite()方法返回一个BulkWriteResult对象,该对象提供有关批量操作的信息。

The following tables describes the fields of a BulkWriteResult object:下表描述了BulkWriteResult对象的字段:

Field字段Description描述
insertedCountThe number of inserted documents插入的文档数量
matchedCountThe number of matched documents匹配的文档数量
modifiedCountThe number of updated documents更新文件的数量
upsertedCountThe number of upserted documents被打乱的文档数量
deletedCountThe number of deleted documents已删除文档的数量

ClientBulkWriteResult

The MongoClient.bulkWrite() method returns a ClientBulkWriteResult object, which includes information about the client bulk write operation.MongoClientbulkWrite()方法返回一个ClientBulkWriteResult对象,其中包含有关客户端批量写入操作的信息。

The following tables describes the fields of a ClientBulkWriteResult object:下表描述了ClientBulkWriteResult对象的字段:

Field字段Description描述
acknowledgedA boolean value indicating whether the bulk write was acknowledged一个布尔值,指示批量写入是否得到确认
insertedCountThe number of inserted documents插入的文档数量
matchedCountThe number of matched documents匹配的文档数量
modifiedCountThe number of updated documents更新文件的数量
upsertedCountThe number of upserted documents被打乱的文档数量
deletedCountThe number of deleted documents已删除文档的数量
insertResultsThe results of each individual successful insert operation每次成功插入操作的结果
updateResultsThe results of each individual successful update operation每个成功更新操作的结果
deleteResultsThe results of each individual successful delete operation每个成功删除操作的结果

Handling Exceptions处理异常

Collection Bulk Write Exceptions集合批量写入异常

If any bulk write operations called on a collection are unsuccessful, the Node.js driver throws a MongoBulkWriteError and does not perform any further operations if the ordered option is set to true. 如果对集合调用的任何批量写入操作都不成功,Node.js驱动程序会抛出MongoBulkWriteError,如果ordered选项设置为true,则不会执行任何进一步的操作。If ordered is set to false, it will attempt to continue with subsequent operations.如果ordered设置为false,它将尝试继续后续操作。

Tip

To learn more about ordered and unordered bulk operations, see the Ordered vs Unordered Operations section in the Bulk Write guide from the MongoDB Server manual.要了解有关有序和无序批量操作的更多信息,请参阅MongoDB Server手册中批量写入指南中的有序与无序操作部分。

A MongoBulkWriteError object contains the following properties:MongoBulkWriteError对象包含以下属性:

Property属性Description描述
messageThe error message.错误消息。
Type: 类型:String
writeErrorsAn array of errors that occurred during the bulk write operation.大容量写入操作期间发生的一系列错误。
Type: 类型:BulkWriteError[]
writeConcernErrorsWrite concern errors that occurred during execution of the bulk write operation.在执行批量写入操作期间发生的写入关注错误。
Type: 类型:WriteConnectionError[]
resultThe results of any successful operations performed before the exception was thrown.在引发异常之前执行的任何成功操作的结果。
Type: 类型:BulkWriteResult[]
errThe underlying error object, which may contain more details.基础错误对象,其中可能包含更多详细信息。
Type: 类型:Error

Client Bulk Write Exceptions客户端批量写入异常

If any bulk write operations called on your client are unsuccessful, the Node.js driver generates a MongoClientBulkWriteError. 如果在客户端上调用的任何批量写入操作都不成功,Node.js驱动程序将生成MongoClientBulkWriteErrorBy default, the driver does not perform any subsequent operations after encountering an error. 默认情况下,驱动程序在遇到错误后不会执行任何后续操作。If you pass the ordered option to the bulkWrite() method and set it to false, the driver continues to attempt the remaining operations.如果将ordered选项传递给bulkWrite()方法并将其设置为false,则驱动程序将继续尝试其余操作。

A MongoClientBulkWriteError object contains the following properties:MongoClientBulkWriteError对象包含以下属性:

Property属性Description描述
writeConcernErrorsAn array of documents specifying each write concern error.指定每个写入关注错误的文档数组。
Type: 类型:Document[]
writeErrorsAn map of errors that occurred during individual write operations.单个写入操作期间发生的错误映射。
Type: 类型:Map<number, ClientBulkWriteError>
partialResultThe partial result of the client bulk write that reflects the operation's progress before the error.客户端批量写入的部分结果,反映了错误发生前的操作进度。
Type: 类型:ClientBulkWriteResult

bulkWrite() Example: Full FilebulkWrite()示例:完整文件

Note

Example Setup示例设置

This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Connect to MongoDB guide. 此示例通过使用连接URI连接到MongoDB的实例。要了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。This example also uses the movies collection in the sample_mflix database included in the Atlas sample datasets. 此示例还使用Atlas示例数据集中包含的sample_mflix数据库中的movies集合。You can load them into your database on the free tier of MongoDB Atlas by following the MongoDB Get Started.您可以按照MongoDB入门指南将它们加载到MongoDB Atlas免费层的数据库中。

The following code is a complete, standalone file that performs a bulk write operation on the theaters collection in the sample_mflix database. 以下代码是一个完整的独立文件,它对sample_mflix数据库中的theaters集合执行批量写入操作。The operations parameter includes examples of insertOne, updateMany, and deleteOne write operations:operations参数包括insertOneupdateManydeleteOne写入操作的示例:

JavaScript
// Bulk write operation批量写入操作

// Import MongoClient from the MongoDB node driver package从MongoDB节点驱动程序包导入MongoClient
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");

// Insert a new document into the "theaters" collection在“剧院”集合中插入新文档
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",
},
},
},
},
},
{
// Update documents that match the specified filter更新与指定筛选器匹配的文档
updateMany: {
filter: { "location.address.zipcode": "44011" },
update: { $set: { is_in_ohio: true } },
upsert: true,
},
},
{
// Delete a document that matches the specified filter删除与指定筛选器匹配的文档
deleteOne: { filter: { "location.address.street1": "221b Baker St" } },
},
]);
// Log the result of the bulk write operation记录批量写入操作的结果
console.log(result);
} finally {
// Close the database connection when the operations are completed or if an error occurs操作完成或发生错误时关闭数据库连接
await client.close();
}
}
run().catch(console.dir);
TypeScript
import { MongoClient } from "mongodb";

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

const client = new MongoClient(uri);

interface Address {
street1: string;
city: string;
state: string;
zipcode: string;
}

interface Theater {
location: { address: Address };
is_in_ohio?: boolean;
}

async function run() {
try {
const database = client.db("sample_mflix");
const theaters = database.collection<Theater>("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: {
// Important: You lose type safety when you use dot notation in queries重要提示:在查询中使用点表示法会失去类型安全性
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);

Running the preceding example results in the following output:运行前面的示例会得到以下输出:

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

Additional Information附加信息

To learn more about bulk operations, see Bulk Write Operations in the MongoDB Server manual.要了解有关批量操作的更多信息,请参阅MongoDB服务器手册中的批量写入操作

API Documentation文档

To learn more about any of the methods or types discussed in this guide, see the following API documentation:要了解有关本指南中讨论的任何方法或类型的更多信息,请参阅以下API文档: