(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
}
}