(mongodb >=1.0.0)
MongoDB\Driver\BulkWrite::__construct — 建立新的 BulkWrite
建構一個新的 MongoDB\Driver\BulkWrite 物件,這是一個可變物件,可以新增一個或多個寫入操作。然後可以使用 MongoDB\Driver\Manager::executeBulkWrite() 執行寫入操作。
options
(陣列)
選項 | 類型 | 說明 | 預設值 |
---|---|---|---|
bypassDocumentValidation | 布林值 |
如果為 此選項在 MongoDB 3.2+ 版本中可用,在較舊的伺服器版本中會被忽略,因為較舊的版本不支援文件層級驗證。 |
false |
comment | 混合 |
一個任意的註釋,用於幫助透過資料庫分析器、currentOp 輸出和日誌追蹤操作。 此選項在 MongoDB 4.4+ 版本中可用,如果在較舊的伺服器版本中指定,則會在執行時導致例外。 |
|
let | 陣列|物件 |
參數名稱和值的映射。值必須是常數或不參考文件欄位的閉包表達式。然後可以在聚合表達式上下文中以變數的形式存取參數(例如 此選項在 MongoDB 5.0+ 版本中可用,如果在較舊的伺服器版本中指定,則會在執行時導致例外。 |
|
ordered | 布林值 | 有序操作 (true ) 在 MongoDB 伺服器上依序執行,而無序操作 (false ) 則以任意順序傳送到伺服器,並且可以並行執行。 |
true |
版本 | 說明 |
---|---|
PECL mongodb 1.14.0 | 新增了 "comment" 和 "let" 選項。 |
PECL mongodb 1.1.0 | 新增了 "bypassDocumentValidation" 選項。 |
範例 #1 MongoDB\Driver\BulkWrite::__construct() 範例
<?php
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->delete([]);
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(
['x' => 2],
['$set' => ['x' => 1]],
['limit' => 1, 'upsert' => false]
);
$bulk->delete(['x' => 1], ['limit' => 1]);
$bulk->update(
['_id' => 3],
['$set' => ['x' => 3]],
['limit' => 1, 'upsert' => true]
);
$manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(1);
try {
$result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
$result = $e->getWriteResult();
// Check if the write concern could not be fulfilled
if ($writeConcernError = $result->getWriteConcernError()) {
printf("%s (%d): %s\n",
$writeConcernError->getMessage(),
$writeConcernError->getCode(),
var_export($writeConcernError->getInfo(), true)
);
}
// Check if any write operations did not complete at all
foreach ($result->getWriteErrors() as $writeError) {
printf("Operation#%d: %s (%d)\n",
$writeError->getIndex(),
$writeError->getMessage(),
$writeError->getCode()
);
}
} catch (MongoDB\Driver\Exception\Exception $e) {
printf("Other error: %s\n", $e->getMessage());
exit;
}
printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Updated %d document(s)\n", $result->getModifiedCount());
printf("Upserted %d document(s)\n", $result->getUpsertedCount());
printf("Deleted %d document(s)\n", $result->getDeletedCount());
?>
上述範例將輸出
Inserted 2 document(s) Updated 1 document(s) Upserted 1 document(s) Deleted 1 document(s)