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 您可以使用批量操作对集合执行多个写入操作。您还可以从客户端运行批量操作,这允许您跨多个命名空间执行批量写入。在MongoDB中,命名空间由数据库名称和集合名称组成,格式为<database>.<collection>.<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 本指南中的示例使用了Atlas示例数据集中包含的movies and users collections in the sample_mflix database, which is included in the Atlas sample datasets. sample_mflix数据库中的movies和users集合。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:此示例执行以下操作:
Specifies two在数组中指定两个InsertOneModelinstances in an array. EachInsertOneModelrepresents a document to insert into themoviescollection in thesample_mflixdatabase.InsertOneModel实例。每个InsertOneModel代表一个要插入到sample_mflix数据库中的movies集合中的文档。Calls the调用bulkWrite()method on themoviescollection and passes an array of models as a parameter.movies集合上的bulkWrite()方法,并将模型数组作为参数传递。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: 2Client 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中设置以指定插入操作的字段:
namespace | String |
name | "insertOne"."insertOne"。String |
document | Document |
Example示例
This example performs the following actions:此示例执行以下操作:
Specifies three在数组中指定三个ClientBulkWriteModelinstances in an array. The first two models represent documents to insert into themoviescollection, and the last model represents a document to insert into theuserscollection.ClientBulkWriteModel实例。前两个模型表示要插入movies集合的文档,最后一个模型表示需要插入users集合的文档。Calls the在客户端调用bulkWrite()method on a client and passes an array of models as a parameter.bulkWrite()方法,并将模型数组作为参数传递。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: 3Bulk 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中设置的字段:
filter | Document |
replacement | Document |
collation | String or Object |
hint | Bson |
upsert | false.false。Boolean |
Example示例
This example performs the following actions:此示例执行以下操作:
Specifies two在数组中指定两个ReplaceOneModelinstances in an array. TheReplaceOneModelinstances contain instructions to replace documents representing movies in themoviescollection.ReplaceOneModel实例。ReplaceOneModel实例包含替换电影集合中代表movies的文档的说明。Calls the调用bulkWrite()method on themoviescollection and passes an array of models as a parameter.movies集合上的bulkWrite()方法,并将模型数组作为参数传递。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: 2Client 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中设置以指定替换操作的字段:
namespace | String |
name | "replaceOne"."replaceOne"。String |
filter | Document |
replacement | Document |
collation | String or Object |
hint | Bson |
Example示例
This example performs the following actions:此示例执行以下操作:
Specifies three在数组中指定三个ClientBulkWriteModelinstances in an array. The first two models contain replacement instructions for documents in themoviescollection, and the last model contains replacement instructions for a document in theuserscollection.ClientBulkWriteModel实例。前两个模型包含movies集合中的文档的替换说明,最后一个模型包含users集合中的文件的替换说明。Calls the在客户端调用bulkWrite()method on a client and passes an array of models as a parameter.bulkWrite()方法,并将模型数组作为参数传递。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: 3Bulk 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. UpdateOneModel或UpdateManyModel。然后,在你的集合上调用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:UpdateOneModel或UpdateManyModel中设置的字段:
filter | UpdateOneModel, only the first matching document will be updated. When specified in an UpdateManyModel, all matching documents will be updated.UpdateOneModel中指定时,只会更新第一个匹配的文档。当在UpdateManyModel中指定时,所有匹配的文档都将被更新。Document |
update | Document |
arrayFilters | Array |
collation | Object |
hint | String or Object |
upsert | false.false。Boolean |
Example示例
This example performs the following actions:此示例执行以下操作:
Specifies an在数组中指定UpdateOneModeland anUpdateManyModelinstance in an array. These models contain instructions to update documents representing movies in themoviescollection.UpdateOneModel和UpdateManyModel实例。这些模型包含更新代表电影集合中电影的文档的说明。Calls the调用bulkWrite()method on themoviescollection and passes an array of models as a parameter.movies集合上的bulkWrite()方法,并将模型数组作为参数传递。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: 2320Client 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中设置以指定更新操作的字段:
namespace | String |
name | "updateOne" or "updateMany"."updateOne"或"updateMany"。String |
filter | name to "updateOne", only the first matching document is updated. name设置为"updateOne",则仅更新第一个匹配的文档。name to "updateMany", all matching documents are updated.name设置为"updateMany",则所有匹配的文档都会更新。Document |
update | Document or Document[] |
arrayFilters | Document[] |
collation | Document |
hint | Document or String |
upsert | false.false。Boolean |
Example示例
This example performs the following actions:此示例执行以下操作:
Specifies two在数组中指定两个ClientBulkWriteModelinstances in an array. The first model specifies an update many operation on themoviescollection, and the second model specifies an update one operation on theuserscollection.ClientBulkWriteModel实例。第一个模型指定了对movies集合的更新多次操作,第二个模型指定对users集合的更新一次操作。Calls the在客户端调用bulkWrite()method on a client and passes an array of models as a parameter.bulkWrite()方法,并将模型数组作为参数传递。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: 2320Bulk 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. DeleteOneModel或DeleteManyModel。Then, 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:DeleteOneModel或DeleteManyModel中设置的字段:
filter | DeleteOneModel, only the first matching document will be deleted. DeleteOneModel中指定时,只会删除第一个匹配的文档。DeleteManyModel, all matching documents will be deleted.DeleteManyModel中指定时,所有匹配的文档都将被删除。Document |
collation | Object |
hint | String or Object |
Example示例
This example performs the following actions:此示例执行以下操作:
Specifies a在数组中指定DeleteOneModeland aDeleteManyModelinstance in an array. These models contain instructions to delete documents in themoviescollection.DeleteOneModel和DeleteManyModel实例。这些模型包含删除电影集合中文档的说明。Calls the调用bulkWrite()method on themoviescollection and passes an array of models as a parameter.movies集合上的bulkWrite()方法,并将模型数组作为参数传递。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: 5538Client 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中设置的字段,以指定删除操作:
namespace | String |
name | "deleteOne" or "deleteMany"."deleteOne"或"deleteMany"。String |
filter | 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",则所有匹配的文档都将被删除。Document |
hint | Document or String |
collation | Document |
Example示例
This example performs the following actions:此示例执行以下操作:
Specifies two在数组中指定两个ClientBulkWriteModelinstances in an array. The first model specifies a delete many operation on themoviescollection, and the second model specifies a delete one operation on theuserscollection.ClientBulkWriteModel实例。第一个模型指定了对movies集合的删除多个操作,第二个模型指定对users集合的删除一个操作。Calls the在客户端调用bulkWrite()method on a client and passes an array of models as a parameter.bulkWrite()方法,并将模型数组作为参数传递。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: 5538Return 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对象的字段:
insertedCount | |
matchedCount | |
modifiedCount | |
upsertedCount | |
deletedCount |
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对象的字段:
acknowledged | |
insertedCount | |
matchedCount | |
modifiedCount | |
upsertedCount | |
deletedCount | |
insertResults | |
updateResults | |
deleteResults |
Handling Exceptions处理异常
Collection Bulk Write Exceptions集合批量写入异常
If any bulk write operations called on a collection are unsuccessful, the Node.js driver throws a 如果对集合调用的任何批量写入操作都不成功,Node.js驱动程序会抛出MongoBulkWriteError and does not perform any further operations if the ordered option is set to true. 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对象包含以下属性:
message | String |
writeErrors | BulkWriteError[] |
writeConcernErrors | WriteConnectionError[] |
result | BulkWriteResult[] |
err | Error |
Client Bulk Write Exceptions客户端批量写入异常
If any bulk write operations called on your client are unsuccessful, the Node.js driver generates a 如果在客户端上调用的任何批量写入操作都不成功,Node.js驱动程序将生成MongoClientBulkWriteError. MongoClientBulkWriteError。By 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对象包含以下属性:
writeConcernErrors | Document[] |
writeErrors | Map<number, ClientBulkWriteError> |
partialResult | 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 此示例还使用Atlas示例数据集中包含的movies collection in the sample_mflix database included in the Atlas sample datasets. 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参数包括insertOne、updateMany和deleteOne写入操作的示例:
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文档: