public function executeBatch($collectionName, $options = [])
{
$databaseName = $this->databaseName === null ? $this->db->defaultDatabaseName : $this->databaseName;
$token = $this->log([$databaseName, $collectionName, 'bulkWrite'], $this->document, __METHOD__);
try {
$this->beginProfile($token, __METHOD__);
$batch = new BulkWrite($options);
$insertedIds = [];
foreach ($this->document as $key => $operation) {
switch ($operation['type']) {
case 'insert':
$insertedIds[$key] = $batch->insert($operation['document']);
break;
case 'update':
$batch->update($operation['condition'], $operation['document'], $operation['options']);
break;
case 'delete':
$batch->delete($operation['condition'], isset($operation['options']) ? $operation['options'] : []);
break;
default:
throw new InvalidConfigException("Unsupported batch operation type '{$operation['type']}'");
}
}
$this->db->open();
$server = $this->db->manager->selectServer($this->getReadPreference());
$writeResult = $server->executeBulkWrite($databaseName . '.' . $collectionName, $batch, $this->getWriteConcern());
$this->endProfile($token, __METHOD__);
} catch (RuntimeException $e) {
$this->endProfile($token, __METHOD__);
throw new Exception($e->getMessage(), $e->getCode(), $e);
}
return ['insertedIds' => $insertedIds, 'result' => $writeResult];
}