文档菜单
文档首页
/ / /
Node.js 驱动
/

执行批量操作

以下bulkWrite() 方法对单个集合执行批量写入操作。此方法减少了应用程序与服务器之间的网络往返次数,从而提高了吞吐量和性能。批量写入仅在将方法传递的所有操作都完成后才返回所有操作的结果。

您可以在 bulkWrite() 中指定以下一个或多个写入操作

  • insertOne

  • updateOne

  • updateMany

  • deleteOne

  • deleteMany

  • replaceOne

bulkWrite() 方法接受以下参数

  • operations:指定要执行的批量写入操作。将每个操作作为数组中的对象传递给 bulkWrite()。有关每个写入操作的语法示例,请参阅批量写入 API 文档.

  • options: 可选 影响操作执行设置,例如写入操作是否按顺序执行和写入关注点。

    默认情况下,MongoDB按照指定顺序逐个执行批量写入操作(串行)。在有顺序的批量写入过程中,如果在处理操作时发生错误,MongoDB将不会处理列表中的剩余操作并返回。相比之下,当ordered设置为false时,MongoDB将继续处理列表中的剩余写入操作。无序操作在理论上是更快的,因为MongoDB可以并行执行它们,但仅在使用写入不依赖于顺序时使用。

如果您创建了一个具有唯一索引约束的索引,您可能会在以下格式的操作期间遇到重复键写入错误:

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

同样,如果您尝试对一个使用模式验证的集合执行批量写入,您可能会遇到与插入或修改的文档格式相关的警告或错误。

以下代码示例在sample_mflix数据库中的theaters集合上执行批量写入操作。示例中调用bulkWrite()包括insertOneupdateManydeleteOne写入操作的示例。

注意

您可以使用此示例连接到MongoDB实例并与包含样本数据的数据库交互。有关连接到您的MongoDB实例和加载样本数据集的更多信息,请参阅用法示例指南.

1// Bulk write operation
2
3// Import MongoClient from the MongoDB node driver package
4const { MongoClient } = require("mongodb");
5
6// Replace the uri string with your MongoDB deployment's connection string
7const uri = "<connection string uri>";
8
9const client = new MongoClient(uri);
10
11async function run() {
12 try {
13 const database = client.db("sample_mflix");
14 const theaters = database.collection("theaters");
15
16 // Insert a new document into the "theaters" collection
17 const result = await theaters.bulkWrite([
18 {
19 insertOne: {
20 document: {
21 location: {
22 address: {
23 street1: "3 Main St.",
24 city: "Anchorage",
25 state: "AK",
26 zipcode: "99501",
27 },
28 },
29 },
30 },
31 },
32 {
33 insertOne: {
34 document: {
35 location: {
36 address: {
37 street1: "75 Penn Plaza",
38 city: "New York",
39 state: "NY",
40 zipcode: "10001",
41 },
42 },
43 },
44 },
45 },
46 {
47 // Update documents that match the specified filter
48 updateMany: {
49 filter: { "location.address.zipcode": "44011" },
50 update: { $set: { is_in_ohio: true } },
51 upsert: true,
52 },
53 },
54 {
55 // Delete a document that matches the specified filter
56 deleteOne: { filter: { "location.address.street1": "221b Baker St" } },
57 },
58 ]);
59 // Log the result of the bulk write operation
60 console.log(result);
61 } finally {
62 // Close the database connection when the operations are completed or if an error occurs
63 await client.close();
64 }
65}
66run().catch(console.dir);
1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8interface Address {
9 street1: string;
10 city: string;
11 state: string;
12 zipcode: string;
13}
14
15interface Theater {
16 location: { address: Address };
17 is_in_ohio?: boolean;
18}
19
20async function run() {
21 try {
22 const database = client.db("sample_mflix");
23 const theaters = database.collection<Theater>("theaters");
24
25 const result = await theaters.bulkWrite([
26 {
27 insertOne: {
28 document: {
29 location: {
30 address: {
31 street1: "3 Main St.",
32 city: "Anchorage",
33 state: "AK",
34 zipcode: "99501",
35 },
36 },
37 },
38 },
39 },
40 {
41 insertOne: {
42 document: {
43 location: {
44 address: {
45 street1: "75 Penn Plaza",
46 city: "New York",
47 state: "NY",
48 zipcode: "10001",
49 },
50 },
51 },
52 },
53 },
54 {
55 updateMany: {
56 // Important: You lose type safety when you use dot notation in queries
57 filter: { "location.address.zipcode": "44011" },
58 update: { $set: { is_in_ohio: true } },
59 upsert: true,
60 },
61 },
62 {
63 deleteOne: {
64 filter: { "location.address.street1": "221b Baker St" },
65 },
66 },
67 ]);
68
69 console.log(result);
70 } finally {
71 await client.close();
72 }
73}
74run().catch(console.dir);

运行前面的示例会产生以下输出

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

返回

监视更改