(mongodb >=1.0.0)
MongoDB\Driver\BulkWrite 收集一个或多个应发送到服务器的写入操作。在添加任意数量的插入、更新和删除操作后,可以通过 MongoDB\Driver\Manager::executeBulkWrite() 执行该集合。
写入操作可以是有序的(默认)或无序的。有序写入操作按提供的顺序发送到服务器,以进行串行执行。如果写入失败,任何剩余的操作都将被中止。无序操作以任意顺序发送到服务器,它们可能并行执行。所有操作尝试后将报告任何发生的错误。
示例 #1 混合写入操作按类型分组
混合写入操作(即插入、更新和删除)将被组装成类型的写入命令,以顺序方式发送到服务器。
<?php
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(['x' => 2], ['$set' => ['x' => 1]]);
$bulk->insert(['_id' => 3, 'x' => 3]);
$bulk->delete(['x' => 1]);
?>
将导致执行四个写入命令(即往返次数)。由于操作是有序的,因此必须在执行前面的更新之前才能发送第三个插入。
示例 #2 有序写入操作导致错误
<?php
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->delete([]);
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 3, 'hello' => 'world']);
$bulk->update(['_id' => 3], ['$set' => ['hello' => 'earth']]);
$bulk->insert(['_id' => 4, 'hello' => 'pluto']);
$bulk->update(['_id' => 4], ['$set' => ['hello' => 'moon']]);
$bulk->insert(['_id' => 3]);
$bulk->insert(['_id' => 4]);
$bulk->insert(['_id' => 5]);
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
try {
$result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
$result = $e->getWriteResult();
// 检查写入关注点是否无法满足
if ($writeConcernError = $result->getWriteConcernError()) {
printf("%s (%d): %s\n",
$writeConcernError->getMessage(),
$writeConcernError->getCode(),
var_export($writeConcernError->getInfo(), true)
);
}
// 检查是否有任何写入操作完全没有完成
foreach ($result->getWriteErrors() as $writeError) {
printf("Operation#%d: %s (%d)\n",
$writeError->getIndex(),
$writeError->getMessage(),
$writeError->getCode()
);
}
} catch (MongoDB\Driver\Exception\Exception $e) {
printf("其他错误: %s\n", $e->getMessage());
exit;
}
printf("插入了 %d 个文档\n", $result->getInsertedCount());
printf("更新了 %d 个文档\n", $result->getModifiedCount());
?>
上面的示例将输出
Operation#7: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 3 } (11000) Inserted 4 document(s) Updated 2 document(s)
如果写入关注点无法满足,上面的示例将输出类似以下内容
waiting for replication timed out (64): array ( 'wtimeout' => true, ) Operation#7: E11000 duplicate key error index: databaseName.collectionName.$_id_ dup key: { : 3 } (11000) Inserted 4 document(s) Updated 2 document(s)
如果我们执行上面的示例,但允许无序写入
<?php
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]);
/* ... */
?>
上面的示例将输出
Operation#7: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 3 } (11000) Operation#8: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 4 } (11000) Inserted 5 document(s) Updated 2 document(s)