PHP Conference Kansai 2025

MongoDB\Driver\Manager::executeBulkWrite

(mongodb >=1.0.0)

MongoDB\Driver\Manager::executeBulkWriteEjecuta una o varias operaciones de escritura

Descripción

final public MongoDB\Driver\Manager::executeBulkWrite(string $namespace, MongoDB\Driver\BulkWrite $bulk, ?array $options = null): MongoDB\Driver\WriteResult

Ejecuta una o varias operaciones de escritura en el servidor primario.

Un MongoDB\Driver\BulkWrite puede ser construido con una o varias operaciones de escritura de tipos variados (por ejemplo, actualizaciones, eliminaciones e inserciones). El controlador intentará enviar las operaciones del mismo tipo al servidor en el menor número de solicitudes posible para optimizar los intercambios.

El valor por omisión de la opción "writeConcern" será deducido a partir de una transacción activa (indicada por la opción "session"), seguida de la URI de conexión.

Parámetros

namespace (string)

Un espacio de nombres completamente cualificado (p. ej. "nombreBaseDatos.nombreColección").

bulk (MongoDB\Driver\BulkWrite)

La/s escritura/s a ejecutar.

options

options
Option Type Description
session MongoDB\Driver\Session

Una sesión a asociar con la operación.

writeConcern MongoDB\Driver\WriteConcern

Un asunto de escritura a aplicar a la operación.

Valores devueltos

Devuelve un MongoDB\Driver\WriteResult en caso de éxito.

Errores/Excepciones

Historial de cambios

Versión Descripción
PECL mongodb 2.0.0 El parámetro options ya no acepta una instancia de MongoDB\Driver\WriteConcern.
PECL mongodb 1.21.0 Pasar un objeto MongoDB\Driver\WriteConcern como options está obsoleto y será eliminado en la versión 2.0.
PECL mongodb 1.4.4 Se lanzará una MongoDB\Driver\Exception\InvalidArgumentException si la opción "session" se utiliza en combinación con un "writeConcern" no-acknowledged.
PECL mongodb 1.4.0 El tercer parámetro es ahora un array de options. Por razones de compatibilidad ascendente, este parámetro siempre aceptará un objeto MongoDB\Driver\WriteConcern.
PECL mongodb 1.3.0 Se lanza una MongoDB\Driver\Exception\InvalidArgumentException si bulk no contiene ninguna operación de escritura. Anteriormente, se lanzaba una MongoDB\Driver\Exception\BulkWriteException.

Ejemplos

Ejemplo #1 Ejemplo de MongoDB\Driver\Manager::executeBulkWrite()

<?php

$bulk
= new MongoDB\Driver\BulkWrite();

$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);

$bulk->update(['x' => 2], ['$set' => ['x' => 1]], ['multi' => false, 'upsert' => false]);
$bulk->update(['x' => 3], ['$set' => ['x' => 3]], ['multi' => false, 'upsert' => true]);
$bulk->update(['_id' => 3], ['$set' => ['x' => 3]], ['multi' => false, 'upsert' => true]);

$bulk->insert(['_id' => 4, 'x' => 2]);

$bulk->delete(['x' => 1], ['limit' => 1]);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 100);
$result = $manager->executeBulkWrite('db.collection', $bulk, ['writeConcern' => $writeConcern]);

printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Matched %d document(s)\n", $result->getMatchedCount());
printf("Updated %d document(s)\n", $result->getModifiedCount());
printf("Upserted %d document(s)\n", $result->getUpsertedCount());
printf("Deleted %d document(s)\n", $result->getDeletedCount());

foreach (
$result->getUpsertedIds() as $index => $id) {
printf('upsertedId[%d]: ', $index);
var_dump($id);
}

/* Si el WriteConcern no ha podido ser satisfecho */
if ($writeConcernError = $result->getWriteConcernError()) {
printf("%s (%d): %s\n", $writeConcernError->getMessage(), $writeConcernError->getCode(), var_export($writeConcernError->getInfo(), true));
}

/* Si una escritura no ha podido hacerse en absoluto */
foreach ($result->getWriteErrors() as $writeError) {
printf("Operation#%d: %s (%d)\n", $writeError->getIndex(), $writeError->getMessage(), $writeError->getCode());
}
?>

El resultado del ejemplo sería algo similar a:

Inserted 3 document(s)
Matched  1 document(s)
Updated  1 document(s)
Upserted 2 document(s)
Deleted  1 document(s)
upsertedId[3]: object(MongoDB\BSON\ObjectId)#5 (1) {
  ["oid"]=>
  string(24) "54d3adc3ce7a792f4d703756"
}
upsertedId[4]: int(3)

Ver también

add a note

User Contributed Notes 1 note

up
2
RJ
5 years ago
If you're trying to figure out how to insert just one object and NOT an array resulting in a bunch of unwanted [0]s in your schema, I'm sorry I cannot help you. I've scoured the SERPs and since MongoDB\Driver\BulkWrite only takes an array it appears there is literally no way to "insertOne" in PHP7, nor a way to pass JUST an object and NOT an array, which may mean you must use a different language or revert to shell commands :-\.

There are several articles where people, apparently mistakenly, refer to "MongoDB\Driver\Client" but neither that nor "MongoDB\Driver\Collections" appear to exist at all. I'm devastated, but if this forces me to downgrade to PHP5 on a brand new project I'll just need to move to a more modern language. :-(

After several hours of this torture I'm now going to spend another hour trying to figure out if I can compose an update query that will collapse the unnecessary array that is being stuck where an object (document) should be. Ug. I realize people using MongoDB have mostly fled PHP, but abandoning the few & loyal among us is really very sad as has been attested to by the unresolved stackoverflow laments that have been going on for years.
To Top