CakeFest 2024: The Official CakePHP Conference

MongoDB\Driver\Manager::executeCommand

(mongodb >=1.0.0)

MongoDB\Driver\Manager::executeCommandExecute a database command

Description

final public MongoDB\Driver\Manager::executeCommand(string $db, MongoDB\Driver\Command $command, array|MongoDB\Driver\ReadPreference|null $options = null): MongoDB\Driver\Cursor

Selects a server according to the "readPreference" option and executes the command on that server. By default, the primary server will be selected.

This method applies no special logic to the command. Although this method accepts "readConcern" and "writeConcern" options, which will be incorporated into the command document, those options will not default to corresponding values from the MongoDB Connection URI nor will the MongoDB server version be taken into account. Users are therefore encouraged to use specific read and/or write command methods if possible.

Liste de paramètres

db (string)

Le nom de la base de données sur laquelle la commande sera exécutée.

command (MongoDB\Driver\Command)

La commande à exécuter.

options

options
Option Type Description
readConcern MongoDB\Driver\ReadConcern

Une préoccupation de lecture à appliquer à l'opération.

Cette option est disponible dans MongoDB 3.2+ et se traduira par une exception au moment de l'exécution si elle est spécifiée pour une version plus ancienne du serveur.

readPreference MongoDB\Driver\ReadPreference

Une préférence de lecture à utiliser pour sélectionner un serveur pour l'opération.

session MongoDB\Driver\Session

Une session à associer à l'opération.

writeConcern MongoDB\Driver\WriteConcern

Une préoccupation d'écriture à appliquer à l'opération.

Avertissement

Si vous utilisez une "session" qui a une transaction en cours, vous ne pouvez pas spécifier l'option "readConcern" ou "writeConcern". Tenter de faire ceci lancera une exception MongoDB\Driver\Exception\InvalidArgumentException. À la place vous devriez définir ces options quand vous créez la transaction avec MongoDB\Driver\Session::startTransaction().

Valeurs de retour

Retourne un MongoDB\Driver\Cursor en cas de succès.

Erreurs / Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Lance une exception MongoDB\Driver\Exception\InvalidArgumentException si l'option "session" est utilisée conjointement avec une préoccupation d'écriture non reconnu.
  • Lance une exception MongoDB\Driver\AuthenticationException si une identification est nécessaire mais qu'elle échoue
  • Lance une exception MongoDB\Driver\ConnectionException si la connexion au serveur échoue pour une autre raison qu'en raison d'un problème d'identification
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command, issuing a write command to a secondary).

Historique

Version Description
PECL mongodb 1.4.4 MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.
PECL mongodb 1.4.0 The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\ReadPreference object.

Exemples

Exemple #1 MongoDB\Driver\Manager::executeCommand() with a command returning a single result document

<?php

$manager
= new MongoDB\Driver\Manager('mongodb://localhost:27017');
$command = new MongoDB\Driver\Command(['ping' => 1]);

try {
$cursor = $manager->executeCommand('admin', $command);
} catch(
MongoDB\Driver\Exception $e) {
echo
$e->getMessage(), "\n";
exit;
}

/* The ping command returns a single result document, so we need to access the
* first result in the cursor. */
$response = $cursor->toArray()[0];

var_dump($response);

?>

L'exemple ci-dessus va afficher :

array(1) {
  ["ok"]=>
  float(1)
}

Exemple #2 MongoDB\Driver\Manager::executeCommand() with a command returning a cursor

<?php

$manager
= new MongoDB\Driver\Manager("mongodb://localhost:27017");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1, 'y' => 'foo']);
$bulk->insert(['x' => 2, 'y' => 'bar']);
$bulk->insert(['x' => 3, 'y' => 'bar']);
$manager->executeBulkWrite('db.collection', $bulk);

$command = new MongoDB\Driver\Command([
'aggregate' => 'collection',
'pipeline' => [
[
'$group' => ['_id' => '$y', 'sum' => ['$sum' => '$x']]],
],
'cursor' => new stdClass,
]);
$cursor = $manager->executeCommand('db', $command);

/* The aggregate command can optionally return its results in a cursor instead
* of a single result document. In this case, we can iterate on the cursor
* directly to access those results. */
foreach ($cursor as $document) {
var_dump($document);
}

?>

L'exemple ci-dessus va afficher :

object(stdClass)#6 (2) {
  ["_id"]=>
  string(3) "bar"
  ["sum"]=>
  int(10)
}
object(stdClass)#7 (2) {
  ["_id"]=>
  string(3) "foo"
  ["sum"]=>
  int(2)
}

Exemple #3 Limiting execution time for a command

The execution time of a command may be limited by specifying a value for "maxTimeMS" in the MongoDB\Driver\Command document. Note that this time limit is enforced on the server side and does not take network latency into account. See » Terminate Running Operations in the MongoDB manual for more information.

<?php

$manager
= new MongoDB\Driver\Manager('mongodb://localhost:27017');

$command = new MongoDB\Driver\Command([
'count' => 'collection',
'query' => ['x' => ['$gt' => 1]],
'maxTimeMS' => 1000,
]);

$cursor = $manager->executeCommand('db', $command);

var_dump($cursor->toArray()[0]);

?>

If the command fails to complete after one second of execution time on the server, a MongoDB\Driver\Exception\ExecutionTimeoutException will be thrown.

Notes

Note: If a secondary readPreference is used, it is the caller's responsibility to ensure that the command can be executed on a secondary. No validation is done by the driver.

Note: This method does not default to using the read preference from the MongoDB Connection URI. Applications in need of that behavior should consider using MongoDB\Driver\Manager::executeReadCommand().

Voir aussi

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top