提示
MongoDB 还提供了 db.collection.bulkWrite() 方法用于执行批量写入操作。
定义
db.collection.initializeUnorderedBulkOp()重要
mongosh 方法
This page documents a
mongoshmethod. This is not the documentation for a language-specific driver, such as Node.js.如需了解 MongoDB API 驱动程序,请参阅特定语言的 MongoDB 驱动程序文档。
为集合初始化并返回新的
Bulk()操作构建器。该构建器可以构造 MongoDB 批量执行的写入操作的无序列表。
兼容性
此命令可用于以下环境中托管的部署:
- MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务
注意
所有 MongoDB Atlas 集群都支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令。
行为
操作顺序
对于无序操作列表,MongoDB 可以按任意顺序并行执行列表中的写入操作。如果操作顺序重要,请改用 db.collection.initializeOrderedBulkOp()。
执行操作
When executing an unordered list of operations, MongoDB groups the operations. With an unordered bulk operation, the operations in the list may be reordered to increase performance. As such, applications should not depend on the ordering when performing unordered bulk operations.
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.
提示
Error Handling
如果在处理其中一个写入操作期间出现错误,MongoDB 将继续处理列表中剩余的写入操作。
例子
以下示例初始化 Bulk() 操作构建器,并添加一系列插入操作以添加多个文档:
var bulk = db.users.initializeUnorderedBulkOp(); bulk.insert( { user: "abc123", status: "A", points: 0 } ); bulk.insert( { user: "ijk123", status: "A", points: 0 } ); bulk.insert( { user: "mop123", status: "P", points: 0 } ); bulk.execute();