PHP Portal » PHP Handbuch » MongoDB::execute

Werbung

MongoDB::execute


()

MongoDB::executeRuns JavaScript code on the database server.

Beschreibung

public array MongoDB::execute ( mixed $code [, array $args = array() ] )

The Mongo database server runs a JavaScript engine. This method allows you to run arbitary JavaScript on the database. This can be useful if you want touch a number of collections lightly, or process some results on the database side to reduce the amount that has to be sent to the client.

Parameter-Liste

code

MongoCode or string to execute.

args

Arguments to be passed to code.

Rückgabewerte

Returns the result of the evaluation.

Beispiele

PHP Code
1
2
$response = $db->execute("function() { return 'Hello, world!'; }"); echo $response['retval'];

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:


Hello, world!

Beispiel #2 Parameter MongoDB::execute() example

The optional array of parameters will be passed to the JavaScript function.

PHP Code
1
2
$response = $db->execute("function(greeting, name) { return greeting+', '+name+'!'; }", array("Good bye", "Joe")); echo $response['retval'];

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:


Good bye, Joe!

Beispiel #3 Scope example

If a MongoCode object is used instead of a string for the first parameter, a scope can be passed in which the JavaScript will be executed.

PHP Code
1
2
3
4
5
6
7
8
$func = "function(greeting, name) { ". "return greeting+', '+name+', says '+greeter;". "}"; $scope = array("greeter" => "Fred"); $code = new MongoCode($func, $scope); $response = $db->execute($code, array("Goodbye", "Joe")); echo $response['retval'];

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:


Goodbye, Joe, says Fred