(mongodb >=1.0.0)
MongoDB\Driver\WriteResult::getWriteErrors — 返回发生的任何写入错误
此函数没有参数。
返回一个包含 MongoDB\Driver\WriteError 对象的数组,这些对象代表写入操作期间遇到的任何写入错误。如果未发生写入错误,则该数组将为空。
示例 #1 MongoDB\Driver\WriteResult::getWriteErrors() 只有一个错误
<?php
$manager = new MongoDB\Driver\Manager;
/* 默认情况下,批量写入操作按顺序串行执行,
* 在遇到第一个错误后执行将停止。
*/
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 3]);
$bulk->insert(['_id' => 4]);
$bulk->insert(['_id' => 4]);
try {
$result = $manager->executeBulkWrite('db.collection', $bulk);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteErrors());
}
?>
上面的示例将输出类似于以下内容
array(1) { [0]=> object(MongoDB\Driver\WriteError)#5 (4) { ["message"]=> string(81) "E11000 duplicate key error collection: db.collection index: _id_ dup key: { : 2 }" ["code"]=> int(11000) ["index"]=> int(2) ["info"]=> NULL } }
示例 #2 MongoDB\Driver\WriteResult::getWriteErrors() 有多个错误
<?php
$manager = new MongoDB\Driver\Manager;
/* "ordered" 选项可用于允许批量写入操作在遇到第一个错误后继续执行。
* 执行。
*/
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]);
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 3]);
$bulk->insert(['_id' => 4]);
$bulk->insert(['_id' => 4]);
try {
$result = $manager->executeBulkWrite('db.collection', $bulk);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteErrors());
}
?>
上面的示例将输出类似于以下内容
array(2) { [0]=> object(MongoDB\Driver\WriteError)#5 (4) { ["message"]=> string(81) "E11000 duplicate key error collection: db.collection index: _id_ dup key: { : 2 }" ["code"]=> int(11000) ["index"]=> int(2) ["info"]=> NULL } [1]=> object(MongoDB\Driver\WriteError)#6 (4) { ["message"]=> string(81) "E11000 duplicate key error collection: db.collection index: _id_ dup key: { : 4 }" ["code"]=> int(11000) ["index"]=> int(5) ["info"]=> NULL } }