<?php
$bulk = new MongoDB\Driver\BulkWrite();
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(['x' => 2], ['$set' => ['x' => 1]], ['multi' => false, 'upsert' => false]);
$bulk->update(['x' => 3], ['$set' => ['x' => 3]], ['multi' => false, 'upsert' => true]);
$bulk->update(['_id' => 3], ['$set' => ['x' => 3]], ['multi' => false, 'upsert' => true]);
$bulk->insert(['_id' => 4, 'x' => 2]);
$bulk->delete(['x' => 1], ['limit' => 1]);
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 100);
$result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
printf("插入了 %d 个文档\n", $result->getInsertedCount());
printf("匹配了 %d 个文档\n", $result->getMatchedCount());
printf("更新了 %d 个文档\n", $result->getModifiedCount());
printf("插入了 %d 个文档\n", $result->getUpsertedCount());
printf("删除了 %d 个文档\n", $result->getDeletedCount());
foreach ($result->getUpsertedIds() as $index => $id) {
printf('upsertedId[%d]: ', $index);
var_dump($id);
}
/* 如果写关注无法满足 */
if ($writeConcernError = $result->getWriteConcernError()) {
printf("%s (%d): %s\n", $writeConcernError->getMessage(), $writeConcernError->getCode(), var_export($writeConcernError->getInfo(), true));
}
/* 如果写入完全无法发生 */
foreach ($result->getWriteErrors() as $writeError) {
printf("操作#%d: %s (%d)\n", $writeError->getIndex(), $writeError->getMessage(), $writeError->getCode());
}
?>
Inserted 3 document(s)
Matched 1 document(s)
Updated 1 document(s)
Upserted 2 document(s)
Deleted 1 document(s)
upsertedId[3]: object(MongoDB\BSON\ObjectId)#5 (1) {
["oid"]=>
string(24) "54d3adc3ce7a792f4d703756"
}
upsertedId[4]: int(3)