PHP Conference Japan 2024

MongoDB\Driver\WriteResult::getWriteErrors

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getWriteErrors返回发生的任何写入错误

描述

final public MongoDB\Driver\WriteResult::getWriteErrors(): array

参数

此函数没有参数。

返回值

返回一个 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
  }
}
添加注释

用户贡献的注释

此页面没有用户贡献的注释。
To Top