Docs 菜单

Bulk()

提示

MongoDB 还提供了 db.collection.bulkWrite() 方法用于执行批量写入操作。

Bulk()

Bulk operations builder used to construct a list of write operations to perform in bulk for a single collection. To instantiate the builder, use either the db.collection.initializeOrderedBulkOp() or the db.collection.initializeUnorderedBulkOp() method.

此命令可用于以下环境中托管的部署:

注意

所有 MongoDB Atlas 集群都支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令

The builder can construct the list of operations as ordered or unordered.

With an ordered operations list, MongoDB executes the write operations in the list serially. If an error occurs during the processing of one of the write operations, MongoDB will return without processing any remaining write operations in the list.

使用 db.collection.initializeOrderedBulkOp() to create a builder for an ordered list of write commands.

执行 ordered 操作列表时,MongoDB 会根据 operation type 和连续性对操作进行分组;也就是说,相同类型的连续 操作会被分在一组。例如,如果有序列表有两个插入操作,后跟一个更新操作,然后是另一个插入操作,则 MongoDB 将这些操作分为三个单独的组:第一组包含两个插入操作,第二组包含更新操作,第三组包含最后一次插入操作。这种行为在未来版本中可能会有所更改。

Bulk() operations in mongosh and comparable methods in the drivers do not have a limit for the number of operations in a group. To see how the operations are grouped for bulk operation execution, call Bulk.getOperations() after the execution.

提示

另请参阅:

在分片集合上执行操作的 ordered 列表通常比执行 unordered 列表慢,因为对于有序列表,每个操作都必须等待前一个操作完成。

With an unordered operations list, MongoDB can execute in parallel, as well as in a nondeterministic order, the write operations in the list. If an error occurs during the processing of one of the write operations, MongoDB will continue to process remaining write operations in the list.

使用 db.collection.initializeUnorderedBulkOp() to create a builder for an unordered list of write commands.

执行 unordered 操作列表时,MongoDB 会对操作进行分组。对于无序批量操作,可以对列表中的操作进行重新排序以提高性能。因此,在执行 unordered 批量操作时,应用程序不应依赖排序。

Bulk() operations in mongosh and comparable methods in the drivers do not have a limit for the number of operations in a group. To see how the operations are grouped for bulk operation execution, call Bulk.getOperations() after the execution.

提示

另请参阅:

Bulk() 可以在分布式事务中使用。

对于 Bulk.insert() 操作,必须存在集合。

对于 Bulk.find.upsert(),如果操作导致 upsert,则必须存在集合。

如果是在事务中运行,则请勿显式设置此操作的写关注。要将写关注与事务一起使用,请参阅事务和写关注。

重要

在大多数情况下,与单文档写入操作相比,分布式事务会产生更高的性能成本,并且分布式事务的可用性不应取代有效的模式设计。在许多情况下,非规范化数据模型(嵌入式文档和数组)仍然是数据和使用案例的最佳选择。换言之,对于许多场景,适当的数据建模将最大限度地减少对分布式事务的需求。

有关其他事务使用注意事项(如运行时间限制和 oplog 大小限制),另请参阅生产注意事项

The Bulk() builder has the following methods:

名称
说明

将插入操作添加到操作列表中。

指定更新或删除操作的查询条件。

将多文档删除操作添加到操作列表中。

将单个文档删除操作添加到操作列表中。

Bulk.find.delete() 的别名。

Bulk.find.deleteOne() 的别名。

将单个文档替换操作添加到操作列表中。

将单文档更新操作添加到操作列表中。

multi 更新操作添加到操作列表中。

为更新操作指定 upsert: true

批量执行操作列表。

返回在 Bulk() 操作对象中执行的写入操作数组。

返回 JSON 文档,其中包含 Bulk() 操作对象中的操作和批次数。

以字符串形式返回 Bulk.toJSON() 结果。