On this page本页内容
db.collection.bulkWrite()
This is a mongosh
method. This is not the documentation for Node.js
or other programming language specific driver methods.
In most cases, mongosh
methods work the same way as the legacy mongo
shell methods. However, some legacy methods are unavailable in mongosh
.
For the legacy mongo
shell documentation, refer to the documentation for the corresponding MongoDB Server release:
For MongoDB API drivers, refer to the language specific MongoDB driver documentation.有关MongoDB API驱动程序,请参阅特定语言的MongoDB驱动程序文档。
Performs multiple write operations with controls for order of execution.使用执行顺序控件执行多个写入操作。
db.collection.bulkWrite()
has the following syntax:具有以下语法:
db.collection.bulkWrite( [ <operation 1>, <operation 2>, ... ], { writeConcern : <document>, ordered : <boolean> } )
operations | array |
| ||
writeConcern | document |
| ||
ordered | boolean |
|
|
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.有关控制写入操作执行顺序的信息,请参阅操作执行。
insertOne
Inserts a single document into the collection.将单个文档插入到集合中。
db.collection.bulkWrite( [ { insertOne : { "document" : <document> } } ] )
updateOne
和updateMany
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
将仅更新第一个匹配的文档。
db.collection.bulkWrite( [ { updateOne : { "filter": <document>, "update": <document or pipeline>, // Changed in 4.2 "upsert": <boolean>, "collation": <document>, // Available starting in 3.4 "arrayFilters": [ <filterdocument1>, ... ], // Available starting in 3.6 "hint": <document|string> // Available starting in 4.2.1 } } ] )
updateMany
updates all documents in the collection that match the filter.updateMany
更新集合中与筛选器匹配的所有文档。
db.collection.bulkWrite( [ { updateMany : { "filter" : <document>, "update" : <document or pipeline>, // Changed in MongoDB 4.2 "upsert" : <boolean>, "collation": <document>, // Available starting in 3.4 "arrayFilters": [ <filterdocument1>, ... ], // Available starting in 3.6 "hint": <document|string> // Available starting in 4.2.1 } } ] )
Notes | |
---|---|
filter | db.collection.find() method are available. db.collection.find() 方法中相同的查询选择器。 |
update |
|
upsert |
|
arrayFilters | |
collation | |
hint |
|
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>, // Available starting in 3.4 "hint": <document|string> // Available starting in 4.2.1 } } ] )
Notes | |
---|---|
filter | db.collection.find() method are available. db.collection.find() 方法中相同的查询选择器。 |
replacement | |
upsert | upsert is false . upser t为false 。 |
collation | |
hint |
|
For details, see to 有关详细信息,请参阅db.collection.replaceOne()
.db.collection.replaceOne()
。
deleteOne
deleteMany
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
deletes all documents in the collection that match the filter.删除集合中与筛选器匹配的所有文档。
db.collection.bulkWrite([ { deleteMany: { "filter" : <document>, "collation" : <document> // Available starting in 3.4 } } ] )
Notes | |
---|---|
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
将创建并填充_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
值。
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()
。
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
.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()
:
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.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
. 100000
。This 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
个操作,则驱动程序会创建两个组,每个组包含100000
个操作。
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.bulkWrite()
写入操作时有限制。
如果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
。
bulkWrite()
write operations have restrictions when used on a time series collection. 写入操作在时间序列集合上使用时有限制。Only 在时间序列集合上只能使用insertOne
can be used on time series collections. insertOne
。All other operations will return a 所有其他操作都将返回WriteError
.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()
对错误抛出BulkWrineError
异常(除非该操作是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.可以在多文档事务中使用。
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
的插入操作或更新操作,则会隐式创建集合。
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
集合包含以下文档:
{ "_id" : 1, "char" : "Brisbane", "class" : "monk", "lvl" : 4 }, { "_id" : 2, "char" : "Eldon", "class" : "alchemist", "lvl" : 3 }, { "_id" : 3, "char" : "Meldane", "class" : "ranger", "lvl" : 3 }
The following 以下bulkWrite()
performs multiple operations on the collection:bulkWrite()
对集合执行多个操作:
try { db.characters.bulkWrite([ { insertOne: { "document": { "_id": 4, "char": "Dithras", "class": "barbarian", "lvl": 4 } } }, { insertOne: { "document": { "_id": 5, "char": "Taeln", "class": "fighter", "lvl": 3 } } }, { updateOne : { "filter" : { "char" : "Eldon" }, "update" : { $set : { "status" : "Critical Injury" } } } }, { deleteOne : { "filter" : { "char" : "Brisbane"} } }, { replaceOne : { "filter" : { "char" : "Meldane" }, "replacement" : { "char" : "Tanys", "class" : "oracle", "lvl": 4 } } } ]); } catch (e) { print(e); }
The operation returns the following:该操作返回以下结果:
{ "acknowledged" : true, "deletedCount" : 1, "insertedCount" : 2, "matchedCount" : 2, "upsertedCount" : 0, "insertedIds" : { "0" : 4, "1" : 5 }, "upsertedIds" : { } }
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
抛出以下重复键异常:
BulkWriteError({ "writeErrors" : [ { "index" : 1, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: guidebook.characters index: _id_ dup key: { _id: 5.0 }", "op" : { "_id" : 5, "char" : "Taeln", "class" : "fighter", "lvl" : 3 } } ], "writeConcernErrors" : [ ], "nInserted" : 1, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
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
集合包含以下文档:
{ "_id" : 1, "char" : "Brisbane", "class" : "monk", "lvl" : 4 }, { "_id" : 2, "char" : "Eldon", "class" : "alchemist", "lvl" : 3 }, { "_id" : 3, "char" : "Meldane", "class" : "ranger", "lvl" : 3 }
The following 以下bulkWrite()
performs multiple unordered
operations on the characters
collection. bulkWrite()
对characters
集合执行多个unordered
操作。Note that one of the 请注意,其中一个insertOne
stages has a duplicate _id
value:insertOne
阶段具有重复的_id
值:
try { db.characters.bulkWrite([ { insertOne: { "document": { "_id": 4, "char": "Dithras", "class": "barbarian", "lvl": 4 } } }, { insertOne: { "document": { "_id": 4, "char": "Taeln", "class": "fighter", "lvl": 3 } } }, { updateOne : { "filter" : { "char" : "Eldon" }, "update" : { $set : { "status" : "Critical Injury" } } } }, { deleteOne : { "filter" : { "char" : "Brisbane"} } }, { replaceOne : { "filter" : { "char" : "Meldane" }, "replacement" : { "char" : "Tanys", "class" : "oracle", "lvl": 4 } } } ], { ordered : false } ); } catch (e) { print(e); }
The operation returns the following:该操作返回以下结果:
BulkWriteError({ "writeErrors" : [ { "index" : 1, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: guidebook.characters index: _id_ dup key: { _id: 4.0 }", "op" : { "_id" : 4, "char" : "Taeln", "class" : "fighter", "lvl" : 3 } } ], "writeConcernErrors" : [ ], "nInserted" : 1, "nUpserted" : 0, "nMatched" : 2, "nModified" : 2, "nRemoved" : 1, "upserted" : [ ] })
Since this was an 由于这是一个unordered
operation, the writes remaining in the queue were processed despite the exception.unordered
操作,因此尽管出现异常,队列中剩余的写入仍被处理。
The enemies
collection contains the following documents:enemies
集合包含以下文档:
{ "_id" : 1, "char" : "goblin", "rating" : 1, "encounter" : 0.24 }, { "_id" : 2, "char" : "hobgoblin", "rating" : 1.5, "encounter" : 0.30 }, { "_id" : 3, "char" : "ogre", "rating" : 3, "encounter" : 0.2 }, { "_id" : 4, "char" : "ogre berserker" , "rating" : 3.5, "encounter" : 0.12}
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毫秒对集合执行多个操作:
try { db.enemies.bulkWrite( [ { updateMany : { "filter" : { "rating" : { $gte : 3} }, "update" : { $inc : { "encounter" : 0.1 } } }, }, { updateMany : { "filter" : { "rating" : { $lt : 2} }, "update" : { $inc : { "encounter" : -0.25 } } }, }, { deleteMany : { "filter" : { "encounter": { $lt : 0 } } } }, { insertOne : { "document" : { "_id" :5, "char" : "ogrekin" , "rating" : 2, "encounter" : 0.31 } } } ], { writeConcern : { w : "majority", wtimeout : 100 } } ); } catch (e) { print(e); }
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
。
BulkWriteError({ "writeErrors" : [ ], "writeConcernErrors" : [ { "code" : 64, "codeName" : "WriteConcernFailed", "errmsg" : "waiting for replication timed out", "errInfo" : { "wtimeout" : true } }, { "code" : 64, "codeName" : "WriteConcernFailed", "errmsg" : "waiting for replication timed out", "errInfo" : { "wtimeout" : true } }, { "code" : 64, "codeName" : "WriteConcernFailed", "errmsg" : "waiting for replication timed out", "errInfo" : { "wtimeout" : true } } ], "nInserted" : 1, "nUpserted" : 0, "nMatched" : 4, "nModified" : 4, "nRemoved" : 1, "upserted" : [ ] })
The result set shows the operations executed since 结果集显示执行的操作,因为writeConcernErrors
errors are not an indicator that any write operations failed.writeConcernErrors
错误并不能指示任何写入操作失败。