On this page本页内容
db.collection.
bulkWrite
()¶mongo
Shell Method
This page documents the 本页记录了mongo
shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. mongo
shell方法,未提及MongoDB Node.js驱动程序(或任何其他驱动程序)方法。For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.有关相应的MongoDB驱动程序API,请参阅特定的MongoDB驱动程序文档。
New in version 3.2.版本3.2中的新功能。
Performs multiple write operations with controls for order of execution.使用执行顺序控件执行多个写操作。
db.collection.bulkWrite()
has the following syntax:语法如下所示:
operations |
array |
| ||
writeConcern |
document |
| ||
ordered |
boolean |
|
Returns: |
|
---|
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.有关控制写入操作执行顺序的信息,请参阅操作执行。
Inserts a single document into the collection.将单个文档插入到集合中。
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
将只更新第一个匹配的文档。
updateMany
updates all documents in the collection that match the filter.更新集合中与筛选器匹配的所有文档。
filter |
db.collection.find() method are available.db.collection.find() 方法中相同的查询选择器可用。 |
update |
|
upsert |
|
arrayFilters |
|
collation |
|
hint |
New in version 4.2.1. |
For details, see 有关详细信息,请参阅db.collection.updateOne()
and db.collection.updateMany()
.db.collection.updateOne()
和db.collection.updateMany()
。
replaceOne
replaces a single document in the collection that matches the filter. replaceOne
替换集合中与筛选器匹配的单个文档。If multiple documents match, 如果多个文档匹配,replaceOne
will replace the first matching document only.replaceOne
将仅替换第一个匹配的文档。
filter |
db.collection.find() method are available.db.collection.find() 方法中相同的查询选择器可用。 |
replacement |
|
upsert |
upsert is false .upsert 为false 。 |
collation |
|
hint |
New in version 4.2.1. |
For details, see to 有关详细信息,请参阅。db.collection.replaceOne()
.
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
将仅删除第一个匹配的文档。
deleteMany
deletes all documents in the collection that match the filter.删除集合中与筛选器匹配的所有文档。
filter |
db.collection.find() method are available.db.collection.find() 方法中相同的查询选择器可用。 |
collation |
For details, see 有关详细信息,请参阅db.collection.deleteOne()
and db.collection.deleteMany()
.db.collection.deleteOne()
和db.collection.deleteMany()
。
_id
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
字段,但如果驱动程序或应用程序不创建并填充_id
,mongod
将创建并填充。
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
值。
The ordered
parameter specifies whether bulkWrite()
will execute operations in order or not. ordered
参数指定bulkWrite()
是否按顺序执行操作。By default, operations are executed in order.默认情况下,操作按顺序执行。
The following code represents a 下面的代码表示包含五个操作的bulkWrite()
with five operations.bulkWrite()
。
In the default 在默认的ordered : true
state, each operation will be executed in order, from the first operation insertOne
to the last operation deleteMany
.ordered:true
状态下,每个操作都将按顺序执行,从第一个操作insertOne
到最后一个操作deleteMany
。
If 如果ordered
is set to false, operations may be reordered by mongod
to increase performance. ordered
设置为false
,mongod
可能会对操作重新排序以提高性能。Applications should not depend on order of operation execution.应用程序不应依赖于操作的执行顺序。
The following code represents an unordered 以下代码表示一个无序的bulkWrite()
with six operations:bulkWrite()
,包含六个操作:
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.deleteOne
或deleteMany
可能会删除更多或更少的文档,具体取决于是在insertOne
、updateOne
、updateMany
还是replaceOne
操作之前或之后运行。
The number of operations in each group cannot exceed the value of the 每个组中的操作数不能超过数据库的maxWriteBatchSize
of the database. maxWriteBatchSize
值。As of MongoDB 3.6, this value is 截至MongoDB 3.6,该值为100,000
. 100,000
。This value is shown in the 此值显示在isMaster.maxWriteBatchSize
field.isMaster.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. 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
值为100,000
时,如果队列包含200,000
个操作,则驱动程序将创建两个组,每个组包含100,000
个操作。
Note
The driver only divides the group into smaller groups when using the high-level API. 在使用高级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.如果直接使用db.runCommand()(例如,在编写驱动程序时),MongoDB在尝试执行超出限制的写入批处理时会抛出错误。
Starting in MongoDB 3.6, once the error report for a single batch grows too large, MongoDB truncates all remaining error messages to the empty string. 从MongoDB 3.6开始,一旦单个批次的错误报告变得太大,MongoDB就会将所有剩余的错误消息截断为空字符串。Currently, begins once there are at least 2 error messages with total size greater than 目前,当至少有2条总大小大于1MB
.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.
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
条件增加了被修改文档的大小,updateOne
和updateMany
可能会抛出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.deleteOne
和deleteMany
如果用于封顶集合,则会抛出WriteError
。
db.collection.bulkWrite()
throws a BulkWriteError
exception on errors (unless the operation is part of a transaction on MongoDB 4.0). db.collection.bulkWrite()
在出现错误时抛出BulkWriteError
异常(除非该操作是MongoDB 4.0上事务的一部分)。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. _id
值。Ordered operations display the single error encountered while unordered operations display each error in an array.有序操作显示遇到的单个错误,而无序操作显示数组中的每个错误。
db.collection.bulkWrite()
can be used inside multi-document transactions.可以在多文档事务中使用。
Important重要的
In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document 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 multi-document transactions.也就是说,对于许多场景,适当地建模数据将最大限度地减少对多文档事务的需求。
For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和oplog大小限制),请参阅生产注意事项。
For feature compatibility version (fcv) 对于功能兼容性版本(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."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无法在同一事务中执行这两个操作。
For fcv 对于fcv"4.2"
or less, the collection must already exist for insert and upsert: true
operations."4.2"
或更低版本,对于insert和upsert:true
操作,集合必须已经存在。
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.要将写关注点用于事务,请参阅事务和写关注点。
Starting in MongoDB 4.2, if a 从MongoDB 4.2开始,如果db.collection.bulkWrite()
operation encounters an error inside a transaction, the method throws a BulkWriteException (same as outside a transaction).db.collection.bulkWrite()
操作在事务内部遇到错误,该方法将抛出BulkWriteException(与事务外部相同)。
In 4.0, if the 在4.0中,如果bulkWrite
operation encounters an error inside a transaction, the error thrown is not wrapped as a BulkWriteException
.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.在事务内部,批量写入中的第一个错误会导致整个批量写入失败并中止事务,即使批量写入是无序的。
The characters
collection in the guidebook
database contains the following documents:guidebook
数据库中的characters
集合包含以下文档:
The following 以下bulkWrite()
performs multiple operations on the collection:bulkWrite()
对集合执行多个操作:
The operation returns the following:该操作返回以下内容:
If the collection had contained a document with 如果在执行大容量写入之前,集合中包含一个带有"_id" : 5"
before executing the bulk write, then when the bulk write is executed, the following duplicate key exception would be thrown for the second insertOne:"_id" : 5"
的文档,那么在执行大容量写入时,将为第二个insertOne
引发以下重复键异常:
Since 由于ordered
is true by default, only the first operation completes successfully. ordered
默认为true
,因此只有第一个操作成功完成。The rest are not executed. 其余的都没有被执行。Running the 使用bulkWrite()
with ordered : false
would allow the remaining operations to complete despite the error.ordered:false
运行bulkWrite()
将允许完成剩余的操作,尽管存在错误。
The characters
collection in the guidebook
database contains the following documents:guidebook
数据库中的characters
集合包含以下文档:
The following 以下bulkWrite()
performs multiple unordered
operations on the characters
collection. bulkWrite()
对characters
集合执行多个无序操作。Note that one of the 请注意,其中一个insertOne
stages has a duplicate _id
value:insertOne
阶段具有重复的_id
值:
The operation returns the following:该操作返回以下内容:
Since this was an 由于这是一个无序操作,因此尽管出现异常,仍会处理队列中剩余的写操作。unordered
operation, the writes remaining in the queue were processed despite the exception.
The code>enemies集合包含以下文档:enemies
collection contains the following documents:
The following 以下bulkWrite()
performs multiple operations on the collection using a write concern value of "majority"
and timeout value of 100 milliseconds:bulkWrite()
使用写入关注值"majority"
和超时值100毫秒对集合执行多个操作:
If the total time required for all required nodes in the replica set to acknowledge the write operation is greater than 如果副本集中所有必需节点确认写入操作所需的总时间大于wtimeout
, the following writeConcernError
is displayed when the wtimeout
period has passed.wtimeout
,则在wtimeout
期间结束后,将显示以下writeConcernError
。
The result set shows the operations executed since 结果集显示了自writeConcernErrors
errors are not an indicator that any write operations failed.writeConcernErrors
错误以来执行的操作,这些错误并不表示任何写入操作都失败。