Perform Bulk Operations执行批量操作

Note

If you specify a callback method, bulkWrite() returns nothing. 如果指定回调方法,bulkWrite()将不返回任何内容。If you do not specify one, this method returns a Promise that resolves to the result object when it completes. 如果未指定,此方法将返回一个Promise,该Promise在完成时解析为结果对象。See our guide on Promises and Callbacks for more information, or the API documentation for information on the result object.有关更多信息,请参阅我们的承诺和回调指南,或参阅API文档以了解有关结果对象的信息。

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.类似地,如果尝试对使用架构验证的集合执行大容量写入,则可能会遇到与插入或修改文档的格式有关的警告或错误。

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实例并加载示例数据集的更多信息,请参阅用法示例指南

import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.用MongoDB部署的连接字符串替换uri字符串。 const uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() { try { await client.connect();
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);
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.用MongoDB部署的连接字符串替换uri字符串。 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 { await client.connect();
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);
Important

Dot Notation Loses Type Safety You lose type-safety for values when you use dot notation in keys. 当在键中使用点表示法时,值的类型安全性将丢失。For more information, see our guide on TypeScript in the driver.有关更多信息,请参阅驱动程序中的TypeScript指南

When you run the preceding example, you should see the following output:运行上述示例时,应看到以下输出:

BulkWriteResult {
  result: {
    ok: 1,
    writeErrors: [],
    writeConcernErrors: [],
    insertedIds: [ [Object], [Object] ],
    nInserted: 2,
    nUpserted: 0,
    nMatched: 1,
    nModified: 1,
    nRemoved: 0,
    upserted: [],
    lastOp: { ts: [Timestamp], t: 17 }
  },
  insertedCount: 2,
  matchedCount: 1,
  modifiedCount: 1,
  deletedCount: 0,
  upsertedCount: 0,
  upsertedIds: {},
  insertedIds: { '0': 5ec4..., '1': 5ec4... },
  n: 2
}