Database Manual / Reference / mongosh Methods / Collections

db.collection.bulkWrite() (mongosh method方法)

Note

New Bulk Write Command in MongoDB 8.0MongoDB 8.0中的新批量写入命令

Starting in MongoDB 8.0, you can use the Mongo.bulkWrite() mongosh method to perform bulk writes across multiple databases and collections. To learn more about different bulk write methods and commands, see Bulk Write Operations.从MongoDB 8.0开始,您可以使用Mongo.bulkWrite() mongosh方法跨多个数据库和集合执行批量写入。要了解有关不同批量写入方法和命令的更多信息,请参阅批量写入操作

Definition定义

db.collection.bulkWrite()

Performs multiple write operations on one collection, with controls for order of execution.对一个集合执行多个写入操作,并控制执行顺序。

Returns:返回
  • A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled.如果操作运行时存在写入关注,则acknowledgedtrue的布尔值,如果禁用写入关注,确认为false的布尔值。
  • A count for each write operation.每次写入操作的计数。
  • An array containing an _id for each successfully inserted or upserted documents.一个数组,包含每个成功插入或插入的文档的_id

Compatibility兼容性

db.collection.bulkWrite() is available in deployments hosted in the following environments:在以下环境中托管的部署中可用:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务

Note

This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.所有MongoDB Atlas集群都支持此命令。有关Atlas支持所有命令的信息,请参阅不支持的命令

  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Note

You can't perform bulk write operations in the Atlas UI. 您无法在Atlas UI中执行批量写入操作。To insert multiple documents, you must insert an array of documents. 要插入多个文档,必须插入一组文档。To learn more, see Create, View, Update, and Delete Documents in the Atlas documentation.要了解更多信息,请参阅Atlas文档中的创建、查看、更新和删除文档

Syntax语法

The bulkWrite() method has the following form:bulkWrite()方法具有以下形式:

db.collection.bulkWrite(
[ <operation 1>, <operation 2>, ... ],
{
writeConcern : <document>,
ordered : <boolean>
}
)

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

Parameter参数Type类型Description描述
operationsarray数组

An array of bulkWrite() write operations.bulkWrite()写入操作的数组。

Valid operations are:有效操作包括:

See Write Operations for usage of each operation有关每个操作的用法,请参阅写入操作

writeConcerndocument文档

Optional. 可选。A document expressing the write concern. Omit to use the default write concern.表达写入关注的文件。省略使用默认写入关注。

Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern.如果在事务中运行,则不要显式设置操作的写入关注。要对事务使用写关注,请参阅事务和写入关注

orderedboolean布尔值

Optional. 可选。A boolean specifying whether the mongod instance should perform an ordered or unordered operation execution. Defaults to true.一个布尔值,指定mongod实例应执行有序还是无序操作。默认为true

See Execution of Operations请参阅操作执行

Behavior行为

bulkWrite() takes an array of write operations and executes each of them. By default operations are executed in order. 获取一组写操作并执行其中的每一个。默认情况下,操作按顺序执行。See Execution of Operations for controlling the order of write operation execution.有关写入操作执行顺序的控制,请参阅操作执行

Write Operations写入操作

insertOne

Inserts a single document into the collection.将单个文档插入到集合中。

db.collection.bulkWrite( [
{ insertOne : { "document" : <document> } }
] )

See db.collection.insertOne().请参阅db.collection.insertOne()

updateOne and updateMany

updateOne

updateOne updates a single document in the collection that matches the filter. If multiple documents match, updateOne will update the first matching document only.updateOne更新集合中与筛选器匹配的单个文档。如果多个文档匹配,updateOne将仅更新第一个匹配的文档。

db.collection.bulkWrite( [
{ updateOne :
{
"filter": <document>,
"update": <document or pipeline>,
"upsert": <boolean>,
"collation": <document>,
"arrayFilters": [ <filterdocument1>, ... ],
"hint": <document|string>
}
}
] )
updateMany

updateMany updates all documents in the collection that match the filter.updateMany会更新集合中与筛选器匹配的所有文档。

db.collection.bulkWrite( [
{ updateMany :
{
"filter" : <document>,
"update" : <document or pipeline>,
"upsert" : <boolean>,
"collation": <document>,
"arrayFilters": [ <filterdocument1>, ... ],
"hint": <document|string>
}
}
] )
Field字段Notes备注
filterThe selection criteria for the update. 更新的选择标准。The same query selectors as in the db.collection.find() method are available.可以使用与db.collection.find()方法中相同的查询选择器
update

The update operation to perform. Can specify either:要执行的更新操作。可以指定以下任一操作:

upsert

Optional. 可选。A boolean to indicate whether to perform an upsert.一个布尔值,用于指示是否执行追加销售。

By default, upsert is false.

arrayFiltersOptional. 可选。An array of filter documents that determine which array elements to modify for an update operation on an array field.一组筛选文档,用于确定在数组字段上进行更新操作时要修改哪些数组元素。
collationOptional. 可选。Specifies the collation to use for the operation.指定用于操作的排序规则
hintOptional. 可选。The index to use to support the update filter. If you specify an index that does not exist, the operation errors.用于支持更新filter索引。如果指定的索引不存在,则操作会出错。

For details, see db.collection.updateOne() and db.collection.updateMany().请参阅db.collection.updateOne()db.collection.updateMany()以了解更多。

replaceOne

replaceOne replaces a single document in the collection that matches the filter. If multiple documents match, replaceOne will replace the first matching document only.替换集合中与筛选器匹配的单个文档。如果多个文档匹配,replaceOne将仅替换第一个匹配的文档。

db.collection.bulkWrite([
{ replaceOne :
{
"filter" : <document>,
"replacement" : <document>,
"upsert" : <boolean>,
"collation": <document>,
"hint": <document|string>
}
}
] )
Field字段Notes备注
filterThe selection criteria for the replacement operation. 更换操作的选择标准。The same query selectors as in the db.collection.find() method are available.可以使用与db.collection.find()方法中相同的查询选择器
replacementThe replacement document. The document cannot contain update operators.替换文件。文档不能包含更新运算符
upsertOptional. 可选。A boolean to indicate whether to perform an upsert. 一个布尔值,用于指示是否执行upsert。By default, upsert is false.默认情况下,upsertfalse
collationOptional. 可选。Specifies the collation to use for the operation.指定用于操作的排序规则
hintOptional. 可选。The index to use to support the update filter. If you specify an index that does not exist, the operation errors.用于支持更新筛选器的索引。如果指定的索引不存在,则操作会出错。

For details, see to db.collection.replaceOne().有关详细信息,请参阅db.collection.replaceOne()

deleteOne and deleteMany

deleteOne

deleteOne deletes a single document in the collection that match the filter. If multiple documents match, deleteOne will delete the first matching document only.删除集合中与筛选器匹配的单个文档。如果多个文档匹配,deleteOne将仅删除第一个匹配的文档。

db.collection.bulkWrite([
{ deleteOne : {
"filter" : <document>,
"collation" : <document> // Available starting in 3.4
} }
] )
deleteMany

deleteMany deletes all documents in the collection that match the filter.删除集合中与筛选器匹配的所有文档。

db.collection.bulkWrite([
{ deleteMany: {
"filter" : <document>,
"collation" : <document> // Available starting in 3.4
} }
] )
Field字段Notes备注
filterThe selection criteria for the delete operation. 删除操作的选择标准。The same query selectors as in the db.collection.find() method are available.可以使用与db.collection.find()方法中相同的查询选择器
collationOptional. 可选。Specifies the collation to use for the operation.指定用于操作的排序规则

For details, see db.collection.deleteOne() and db.collection.deleteMany().有关详细信息,请参阅db.collection.deleteOne()db.collection.deleteMany()

_id Field字段

If the document does not specify an _id field, then mongod adds the _id field and assign a unique ObjectId() for the document before inserting or upserting it. 如果文档没有指定_id字段,则mongod会添加_id字段,并在插入或升级文档之前为文档分配一个唯一的ObjectId()Most drivers create an ObjectId and insert the _id field, but the mongod will create and populate the _id if the driver or application does not.大多数驱动程序创建一个ObjectId并插入_id字段,但如果驱动程序或应用程序没有创建并填充_idmongod将创建并填充该_id

If the document contains an _id field, the _id value must be unique within the collection to avoid duplicate key error.如果文档包含_id字段,则_id值在集合中必须是唯一的,以避免重复键错误。

Update or replace operations cannot specify an _id value that differs from the original document.更新或替换操作不能指定与原始文档不同的_id值。

Execution of Operations操作执行

The ordered parameter specifies whether bulkWrite() will execute operations in order or not. By default, operations are executed in order.ordered参数指定bulkWrite()是否按顺序执行操作。默认情况下,操作按顺序执行。

The following code represents a bulkWrite() with five operations.以下代码表示一个包含五个操作的bulkWrite()

db.collection.bulkWrite(
[
{ insertOne : <document> },
{ updateOne : <document> },
{ updateMany : <document> },
{ replaceOne : <document> },
{ deleteOne : <document> },
{ deleteMany : <document> }
]
)

In the default ordered : true state, each operation will be executed in order, from the first operation insertOne to the last operation deleteMany.在默认的order:true状态下,每个操作都将按顺序执行,从第一个操作insertOne到最后一个操作deleteMany

If ordered is set to false, operations may be reordered by mongod to increase performance. Applications should not depend on order of operation execution.如果ordered设置为falsemongod可能会重新排序操作以提高性能。应用程序不应依赖于操作执行的顺序。

The following code represents an unordered bulkWrite() with six operations:以下代码表示具有六个操作的无序bulkWrite()

db.collection.bulkWrite(
[
{ insertOne : <document> },
{ updateOne : <document> },
{ updateMany : <document> },
{ replaceOne : <document> },
{ deleteOne : <document> },
{ deleteMany : <document> }
],
{ ordered : false }
)

With ordered : false, the results of the operation may vary. 使用ordered : false,操作结果可能会有所不同。For example, the deleteOne or deleteMany may remove more or fewer documents depending on whether the run before or after the insertOne, updateOne, updateMany, or replaceOne operations.例如,deleteOnedeleteMany可能会删除更多或更少的文档,具体取决于运行是在insertOneupdateOneupdateMany还是replaceOne操作之前还是之后。

The number of operations in each group cannot exceed the value of the maxWriteBatchSize of the database. 每个组中的操作数不能超过数据库的maxWriteBatchSize值。The default value of maxWriteBatchSize is 100,000. maxWriteBatchSize的默认值为100000This value is shown in the hello.maxWriteBatchSize field.此值显示在hello.maxWriteBatchSize字段中。

This limit prevents issues with oversized error messages. If a group exceeds this limit, the client driver divides the group into smaller groups with counts less than or equal to the value of the limit. 此限制可防止出现错误消息过大的问题。如果一个组超过此限制,客户端驱动程序会将该组划分为计数小于或等于限制值的较小组。For example, with the maxWriteBatchSize value of 100,000, if the queue consists of 200,000 operations, the driver creates 2 groups, each with 100,000 operations.例如,当maxWriteBatchSize值为100000时,如果队列包含200000个操作,驱动程序将创建2个组,每个组包含100000个操作。

Note

The driver only divides the group into smaller groups when using the high-level API. If using db.runCommand() directly (for example, when writing a driver), MongoDB throws an error when attempting to execute a write batch which exceeds the limit.当使用高级API时,驱动程序仅将组划分为较小的组。如果直接使用db.runCommand()(例如,在编写驱动程序时),MongoDB在尝试执行超过限制的写批时会抛出错误。

If the error report for a single batch grows too large, MongoDB truncates all remaining error messages to the empty string. If there are at least two error messages with total size greater than 1MB, they are trucated.如果单个批的错误报告太大,MongoDB会将所有剩余的错误消息截断为空字符串。如果至少有两条总大小大于1MB的错误消息,则会对其进行截断。

The sizes and grouping mechanics are internal performance details and are subject to change in future versions.尺寸和分组机制是内部性能细节,在未来的版本中可能会发生变化。

Executing an ordered list of operations on a sharded collection will generally be slower than executing an unordered list since with an ordered list, each operation must wait for the previous operation to finish.在分片集合上执行ordered(有序)操作列表通常比执行unordered(无序)列表慢,因为使用有序列表,每个操作都必须等待前一个操作完成。

Capped Collections封顶集合

bulkWrite() write operations have restrictions when used on a capped collection.封顶集合上使用写操作时有限制。

updateOne and updateMany throw a WriteError if the update criteria increases the size of the document being modified.如果update条件增加了正在修改的文档的大小,updateOneupdateMany会抛出WriteError

replaceOne throws a WriteError if the replacement document has a larger size than the original document.如果replacement文档的大小大于原始文档,replaceOne将抛出WriteError

deleteOne and deleteMany throw a WriteError if used on a capped collection.如果在封顶集合上使用deleteOnedeleteMany,则会抛出WriteError

Error Handling错误处理

db.collection.bulkWrite() throws a BulkWriteError exception on errors. 在出现错误时抛出BulkWriteError异常。See Error Handling inside Transactions.请参阅事务内部的错误处理

Excluding write concern errors, ordered operations stop after an error, while unordered operations continue to process any remaining write operations in the queue, unless when run inside a transaction. See Error Handling inside Transactions.写入关注错误外,有序操作在错误发生后停止,而无序操作继续处理队列中的任何剩余写操作,除非在事务中运行。请参阅事务内部的错误处理

Write concern errors are displayed in the writeConcernErrors field, while all other errors are displayed in the writeErrors field. writeConcernErrors字段中显示写入关注错误,而所有其他错误都显示在writeErrors字段。If an error is encountered, the number of successful write operations are displayed instead of the inserted _id values. Ordered operations display the single error encountered while unordered operations display each error in an array.如果遇到错误,将显示成功写入操作的次数,而不是插入的_id值。有序操作显示遇到的单个错误,而无序操作显示数组中的每个错误。

Schema Validation Errors架构验证错误

If your collection uses schema validation and has validationAction set to error, inserting an invalid document or updating a document with invalid values throws an error. 如果集合使用架构验证,并且将validationAction设置为error,则插入无效文档或用无效值更新文档会引发错误。Operations preceding the invalid operation in the operations array are executed and written to the collection. operations数组中无效操作之前的操作将被执行并写入集合。The ordered field determines if the remaining operations are executed.ordered字段决定是否执行其余操作。

Transactions事务

db.collection.bulkWrite() can be used inside distributed transactions.db.collection.bulkWrite()可以在分布式事务中使用。

Important

In most cases, a distributed transaction incurs a greater performance cost over single document writes, and the availability of distributed transactions should not be a replacement for effective schema design. 在大多数情况下,分布式事务比单文档写入产生更大的性能成本,分布式事务的可用性不应取代有效的模式设计。For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. 对于许多场景,非规范化数据模型(嵌入式文档和数组)将继续是数据和用例的最佳选择。That is, for many scenarios, modeling your data appropriately will minimize the need for distributed transactions.也就是说,对于许多场景,适当地对数据进行建模将最大限度地减少对分布式事务的需求。

For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和oplog大小限制),另请参阅生产注意事项

Inserts and Upserts within Transactions事务中的插入和追加

For feature compatibility version (fcv) "4.4" and greater, if an insert operation or update operation with upsert: true is run in a transaction against a non-existing collection, the collection is implicitly created.对于功能兼容性版本(fcv)"4.4"及更高版本,如果在事务中对不存在的集合运行带有upsert:true的插入操作或更新操作,则隐式创建该集合。

Note

You cannot create new collections in cross-shard write transactions. For example, if you write to an existing collection in one shard and implicitly create a collection in a different shard, MongoDB cannot perform both operations in the same transaction.您无法在跨分片写入事务中创建新集合。例如,如果你在一个分片中写入一个现有的集合,并在另一个分片中隐式创建一个集合,MongoDB无法在同一事务中执行这两个操作。

Write Concerns and Transactions撰写入关注和事务

Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern.如果在事务中运行,则不要显式设置操作的写入关注。要对事务使用写关注,请参阅事务和写关注

Error Handling inside Transactions事务内部错误处理

Starting in MongoDB 4.2, if a db.collection.bulkWrite() operation encounters an error inside a transaction, the method throws a BulkWriteException (same as outside a transaction).从MongoDB 4.2开始,如果db.collection.bulkWrite()操作在事务内部遇到错误,该方法会抛出BulkWriteException(与事务外部相同)。

In 4.0, if the bulkWrite operation encounters an error inside a transaction, the error thrown is not wrapped as a BulkWriteException.在4.0中,如果bulkWrite操作在事务中遇到错误,则抛出的错误不会被包装为BulkWriteException

Inside a transaction, the first error in a bulk write causes the entire bulk write to fail and aborts the transaction, even if the bulk write is unordered.在事务内部,批量写入中的第一个错误会导致整个批量写入失败并中止事务,即使批量写入是无序的。

Examples示例

Ordered Bulk Write Example有序批量写入示例

It is important that you understand bulkWrite() operation ordering and error handling. By default, bulkWrite() runs an ordered list of operations:了解bulkWrite()操作顺序和错误处理非常重要。默认情况下,bulkWrite()运行一个有序的操作列表:

  • Operations run serially.操作按顺序运行。
  • If an operation has an error, that operation and any following operations are not run.如果某个操作有错误,则该操作和任何后续操作都不会运行。
  • Operations listed before the error operation are completed.错误操作完成之前列出的操作。

The bulkWrite() examples use the pizzas collection:bulkWrite()示例使用pizzas集合:

db.pizzas.insertMany( [
{ _id: 0, type: "pepperoni", size: "small", price: 4 },
{ _id: 1, type: "cheese", size: "medium", price: 7 },
{ _id: 2, type: "vegan", size: "large", price: 8 }
] )

The following db.collection.bulkWrite() example runs the following operations on the pizzas collection:以下db.collection.bulkWrite()示例对pizzas集合运行以下操作:

  • Adds two documents using insertOne.使用insertOne添加两个文档。
  • Updates a document using updateOne.使用updateOne更新文档。
  • Deletes a document using deleteOne.使用deleteOne删除文档。
  • Replaces a document using replaceOne.使用replaceOne替换文档。
try {
db.pizzas.bulkWrite( [
{ insertOne: { document: { _id: 3, type: "beef", size: "medium", price: 6 } } },
{ insertOne: { document: { _id: 4, type: "sausage", size: "large", price: 10 } } },
{ updateOne: {
filter: { type: "cheese" },
update: { $set: { price: 8 } }
} },
{ deleteOne: { filter: { type: "pepperoni"} } },
{ replaceOne: {
filter: { type: "vegan" },
replacement: { type: "tofu", size: "small", price: 4 }
} }
] )
} catch( error ) {
print( error )
}

Example output, which includes a summary of the completed operations:示例输出,其中包括已完成操作的摘要:

{
acknowledged: true,
insertedCount: 2,
insertedIds: { '0': 3, '1': 4 },
matchedCount: 2,
modifiedCount: 2,
deletedCount: 1,
upsertedCount: 0,
upsertedIds: {}
}

If the collection already contained a document with an _id of 4 before running the previous bulkWrite() example, the following duplicate key exception is returned for the second insertOne operation:如果在运行前面的bulkWrite()示例之前,集合中已经包含_id4的文档,则第二次insertOne操作将返回以下重复键异常:

writeErrors: [
WriteError {
err: {
index: 1,
code: 11000,
errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 4 }',
op: { _id: 4, type: 'sausage', size: 'large', price: 10 }
}
}
],
result: BulkWriteResult {
result: {
ok: 1,
writeErrors: [
WriteError {
err: {
index: 1,
code: 11000,
errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 4 }',
op: { _id: 4, type: 'sausage', size: 'large', price: 10 }
}
}
],
writeConcernErrors: [],
insertedIds: [ { index: 0, _id: 3 }, { index: 1, _id: 4 } ],
nInserted: 1,
nUpserted: 0,
nMatched: 0,
nModified: 0,
nRemoved: 0,
upserted: []
}
}

Because the bulkWrite() example is ordered, only the first insertOne operation is completed.因为bulkWrite()示例是有序的,所以只完成了第一个insertOne操作。

To complete all operations that do not have errors, run bulkWrite() with ordered set to false. For an example, see the following section.要完成所有没有错误的操作,请在有序设置为false的情况下运行bulkWrite()。有关示例,请参阅以下部分。

Unordered Bulk Write Example无序批量写入示例

To specify an unordered bulkWrite(), set ordered to false.要指定无序bulkWrite(),请将ordered设置为false

In an unordered bulkWrite() list of operations:在无序bulkWrite()操作列表中:

  • Operations can run in parallel (not guaranteed). For details. See Ordered vs Unordered Operations.操作可以并行运行(不保证)。了解详情。请参阅有序操作与无序操作
  • Operations with errors are not completed.有错误的操作未完成。
  • All operations without errors are completed.所有没有错误的操作都已完成。

Continuing the pizzas collection example, drop and recreate the collection:继续pizzas集合示例,删除并重新创建集合:

db.pizzas.insertMany( [
{ _id: 0, type: "pepperoni", size: "small", price: 4 },
{ _id: 1, type: "cheese", size: "medium", price: 7 },
{ _id: 2, type: "vegan", size: "large", price: 8 }
] )

In the following example:在以下示例中:

  • bulkWrite() runs unordered operations on the pizzas collection.pizzas集合执行无序操作。
  • The second insertOne operation has the same _id as the first insertOne, which causes a duplicate key error.第二个insertOne操作的_id与第一个insertOne相同,这会导致重复键错误。
try {
db.pizzas.bulkWrite( [
{ insertOne: { document: { _id: 3, type: "beef", size: "medium", price: 6 } } },
{ insertOne: { document: { _id: 3, type: "sausage", size: "large", price: 10 } } },
{ updateOne: {
filter: { type: "cheese" },
update: { $set: { price: 8 } }
} },
{ deleteOne: { filter: { type: "pepperoni"} } },
{ replaceOne: {
filter: { type: "vegan" },
replacement: { type: "tofu", size: "small", price: 4 }
} }
],
{ ordered: false } )
} catch( error ) {
print( error )
}

Example output, which includes the duplicate key error and a summary of the completed operations:示例输出,其中包括重复键错误和已完成操作的摘要:

writeErrors: [
WriteError {
err: {
index: 1,
code: 11000,
errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 3 }',
op: { _id: 3, type: 'sausage', size: 'large', price: 10 }
}
}
],
result: BulkWriteResult {
result: {
ok: 1,
writeErrors: [
WriteError {
err: {
index: 1,
code: 11000,
errmsg: 'E11000 duplicate key error collection: test.pizzas index: _id_ dup key: { _id: 3 }',
op: { _id: 3, type: 'sausage', size: 'large', price: 10 }
}
}
],
writeConcernErrors: [],
insertedIds: [ { index: 0, _id: 3 }, { index: 1, _id: 3 } ],
nInserted: 1,
nUpserted: 0,
nMatched: 2,
nModified: 2,
nRemoved: 1,
upserted: []
}
}

The second insertOne operation fails because of the duplicate key error. In an unordered bulkWrite(), any operation without an error is completed.由于重复键错误,第二次insertOne操作失败。在无序bulkWrite()中,任何没有错误的操作都会完成。

Write Concern Errors in Sharded Clusters分片集群中的写入关注错误

Changed in version 8.1.2.在版本8.1.2中的更改。

When db.collection.bulkWrite() executes on mongos in a sharded cluster, a writeConcernError is always reported in the response, even when one or more other errors occur. db.collection.bulkWrite()在分片集群中的mongos上执行时,即使出现一个或多个其他错误,也总是在响应中报告writeConcernErrorIn previous releases, other errors sometimes caused db.collection.bulkWrite() to not report write concern errors.在以前的版本中,其他错误有时会导致db.collection.bulkWrite()不报告写入关注错误。

For example, if a document fails validation, triggering a DocumentValidationFailed error, and a write concern error also occurs, both the DocumentValidationFailed error and the writeConcernError are returned in the top-level field of the response.例如,如果文档验证失败,触发DocumentValidationFailed错误,并且还发生写入关注错误,则DocumentValidationFailure错误和writeConcernError都会在响应的顶级字段中返回。

Bulk Write with Write Concern Example带有写入关注的批量写入示例

Continuing the pizzas collection example, drop and recreate the collection:继续pizzas集合示例,删除并重新创建集合:

db.pizzas.insertMany( [
{ _id: 0, type: "pepperoni", size: "small", price: 4 },
{ _id: 1, type: "cheese", size: "medium", price: 7 },
{ _id: 2, type: "vegan", size: "large", price: 8 }
] )

The following bulkWrite() example runs operations on the pizzas collection and sets a "majority" write concern with a 100 millisecond timeout:以下bulkWrite()示例对pizzas集合运行操作,并设置一个"majority"写入关注超时100毫秒:

try {
db.pizzas.bulkWrite( [
{ updateMany: {
filter: { size: "medium" },
update: { $inc: { price: 0.1 } }
} },
{ updateMany: {
filter: { size: "small" },
update: { $inc: { price: -0.25 } }
} },
{ deleteMany: { filter: { size: "large" } } },
{ insertOne: {
document: { _id: 4, type: "sausage", size: "small", price: 12 }
} } ],
{ writeConcern: { w: "majority", wtimeout: 100 } }
)
} catch( error ) {
print( error )
}

If the time for the majority of replica set members to acknowledge the operations exceeds wtimeout, the example returns a write concern error and a summary of completed operations:如果大多数副本集成员确认操作的时间超过wtimeout,则该示例将返回一个写入关注错误和已完成操作的摘要:

result: BulkWriteResult {
result: {
ok: 1,
writeErrors: [],
writeConcernErrors: [
WriteConcernError {
err: {
code: 64,
codeName: 'WriteConcernTimeout',
errmsg: 'waiting for replication timed out',
errInfo: { wtimeout: true, writeConcern: [Object] }
}
}
],
insertedIds: [ { index: 3, _id: 4 } ],
nInserted: 0,
nUpserted: 0,
nMatched: 2,
nModified: 2,
nRemoved: 0,
upserted: [],
opTime: { ts: Timestamp({ t: 1660329086, i: 2 }), t: Long("1") }
}
}