MongoDB\Driver\Manager: : executeCommand
(mongodb >=1.0.0)
MongoDB\Driver\Manager::executeCommand — Execute a database command
Description
$db
, MongoDB\Driver\Command $command
[, array $options
= array()
] ) : MongoDB\Driver\CursorSelects a server according to the "readPreference" option and executes the command on that server. By default, the read preference from the MongoDB Connection URI will be used.
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.
Parameters
-
db
(string) -
The name of the database on which to execute the command.
-
command
(MongoDB\Driver\Command) -
The command to execute.
-
options
-
options Option Type Description readConcern MongoDB\Driver\ReadConcern A read concern to apply to the operation.
This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.
readPreference MongoDB\Driver\ReadPreference A read preference to use for selecting a server for the operation.
session MongoDB\Driver\Session A session to associate with the operation.
writeConcern MongoDB\Driver\WriteConcern A write concern to apply to the operation.
WarningIf you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().
Errors/Exceptions
- Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
- Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
- Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
- Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
- Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
- Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command, issuing a write command to a secondary).
Changelog
Version | Description |
---|---|
1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern. |
1.4.0 |
The third parameter is now an options array.
For backwards compatibility, this paramater will still accept a
MongoDB\Driver\ReadPreference object.
|
Examples
Example #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);
?>
The above example will output:
array(1) { ["ok"]=> float(1) }
Example #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);
}
?>
The above example will output:
object(stdClass)#6 (2) { ["_id"]=> string(3) "bar" ["sum"]=> int(10) } object(stdClass)#7 (2) { ["_id"]=> string(3) "foo" ["sum"]=> int(2) }
Example #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 thecommand
can be executed on a secondary. No validation is done by the driver.
See Also
- MongoDB\Driver\Command
- MongoDB\Driver\Cursor
- MongoDB\Driver\Manager::executeReadCommand() - Execute a database command that reads
- MongoDB\Driver\Manager::executeReadWriteCommand() - Execute a database command that reads and writes
- MongoDB\Driver\Manager::executeWriteCommand() - Execute a database command that writes
- MongoDB\Driver\Server::executeCommand() - Execute a database command on this server
Vertaling niet beschikbaar
De PHP-handleiding is nog niet in het Nederlands vertaald, dus het scherm is in het Engels. Als u wilt, kunt u het ook in het Frans of in het Duits raadplegen.
Als je de moed voelt, kun je je vertaling aanbieden ;-)
Nederlandse vertaling
U hebt gevraagd om deze site in het Nederlands te bezoeken. Voor nu wordt alleen de interface vertaald, maar nog niet alle inhoud.Als je me wilt helpen met vertalingen, is je bijdrage welkom. Het enige dat u hoeft te doen, is u op de site registreren en mij een bericht sturen waarin u wordt gevraagd om u toe te voegen aan de groep vertalers, zodat u de gewenste pagina's kunt vertalen. Een link onderaan elke vertaalde pagina geeft aan dat u de vertaler bent en heeft een link naar uw profiel.
Bij voorbaat dank.
Document heeft de 30/01/2003 gemaakt, de laatste keer de 26/10/2018 gewijzigd
Bron van het afgedrukte document:https://www.gaudry.be/nl/php-rf-mongodb-driver-manager.executecommand.html
De infobrol is een persoonlijke site waarvan de inhoud uitsluitend mijn verantwoordelijkheid is. De tekst is beschikbaar onder CreativeCommons-licentie (BY-NC-SA). Meer info op de gebruiksvoorwaarden en de auteur.
Referenties
Deze verwijzingen en links verwijzen naar documenten die geraadpleegd zijn tijdens het schrijven van deze pagina, of die aanvullende informatie kunnen geven, maar de auteurs van deze bronnen kunnen niet verantwoordelijk worden gehouden voor de inhoud van deze pagina.
De auteur Deze site is als enige verantwoordelijk voor de manier waarop de verschillende concepten, en de vrijheden die met de referentiewerken worden genomen, hier worden gepresenteerd. Vergeet niet dat u meerdere broninformatie moet doorgeven om het risico op fouten te verkleinen.