MongoDB::execute
(PECL mongo >=0.9.3)
MongoDB::execute — Runs JavaScript code on the database server.
Описание
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.
Running JavaScript in the database takes a write lock, meaning it blocks other operations. Make sure you consider this before running a long script.
This is a wrapper for a database command. This method is basically:
<?php
public function execute($code, $args) {
return $this->command(array('$eval' => $code, 'args' => $args));
}
?>
MongoDB implies a return statement if you have a single statement on a single line. This can cause some unintuitive behavior. For example, this returns "foo":
<?php
$db->execute('"foo";');
?>
However, these return NULL
:
<?php
$db->execute('"bar"; "foo";'); // more than one statement
$db->execute('db.foo.count(
);'); // more than one line
?>
To avoid surprising behavior, it is best not to depend on MongoDB to decide what to return, but to explicitly state a return value. In the examples above, we can change them to:
<?php
$db->execute('"bar"; return "foo";');
$db->execute('return db.foo.count(
);');
?>
Now the first statement will return "foo" and the second statement will return a count of the "foo" collection.
Возвращаемые значения
Returns the result of the evaluation.
Примеры
Пример #1 Simple MongoDB::execute() example
<?php
$response = $db->execute("function() { return 'Hello, world!'; }");
echo $response['retval'];
?>
Результатом выполнения данного примера будет что-то подобное:
Hello, world!
Пример #2 Parameter MongoDB::execute() example
The optional array of parameters will be passed to the JavaScript function.
<?php
$response = $db->execute("function(greeting, name) { return greeting+', '+name+'!'; }", array("Good bye", "Joe"));
echo $response['retval'];
?>
Результатом выполнения данного примера будет что-то подобное:
Good bye, Joe!
Пример #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
$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'];
?>
Результатом выполнения данного примера будет что-то подобное:
Goodbye, Joe, says Fred
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Расширения для работы с базами данных отдельных производителей
- MongoDB
- Базовые классы
- Функция MongoDB::authenticate() - Log in to this database
- Функция MongoDB::command() - Execute a database command
- Функция MongoDB::__construct() - Creates a new database
- Функция MongoDB::createCollection() - Creates a collection
- Функция MongoDB::createDBRef() - Creates a database reference
- Функция MongoDB::drop() - Drops this database
- Функция MongoDB::dropCollection() - Drops a collection [deprecated]
- Функция MongoDB::execute() - Runs JavaScript code on the database server.
- Функция MongoDB::forceError() - Creates a database error
- Функция MongoDB::__get() - Gets a collection
- MongoDB::getCollectionInfo
- Функция MongoDB::getCollectionNames() - Get all collections from this database
- Функция MongoDB::getDBRef() - Fetches the document pointed to by a database reference
- Функция MongoDB::getGridFS() - Fetches toolkit for dealing with files stored in this database
- Функция MongoDB::getProfilingLevel() - Gets this database's profiling level
- Функция MongoDB::getReadPreference() - Get the read preference for this database
- Функция MongoDB::getSlaveOkay() - Get slaveOkay setting for this database
- Функция MongoDB::getWriteConcern() - Get the write concern for this database
- Функция MongoDB::lastError() - Check if there was an error on the most recent db operation performed
- Функция MongoDB::listCollections() - Gets an array of all MongoCollections for this database
- Функция MongoDB::prevError() - Checks for the last error thrown during a database operation
- Функция MongoDB::repair() - Repairs and compacts this database
- Функция MongoDB::resetError() - Clears any flagged errors on the database
- Функция MongoDB::selectCollection() - Gets a collection
- Функция MongoDB::setProfilingLevel() - Sets this database's profiling level
- Функция MongoDB::setReadPreference() - Set the read preference for this database
- Функция MongoDB::setSlaveOkay() - Change slaveOkay setting for this database
- Функция MongoDB::setWriteConcern() - Set the write concern for this database
- Функция MongoDB::__toString() - The name of this database
Коментарии
In 1.7.2, a nolock option was added to eval. To use nolock you have to use the command interface directly:
db.runCommand({$eval: function() {return 42;}, nolock: true})
or with args
db.runCommand({$eval: function(x,y) {return x*y;}, args: [6,7], nolock: true})
$m = new MongoClient();
$db = $m->test;
$inset = "db.getCollection('foo').insert({'name':'nanhe','age':30});";
$response = $db->execute($inset);
print_r($response); //Array ( [retval] => [ok] => 1 )
$response = $m->test->execute("db.getCollection('foo').insert({'name':'happy','age':18});");
print_r($response); //Array ( [retval] => [ok] => 1 )
$response = $m->test->execute("db.foo.insert({'name':'prince','age':16});");
print_r($response); //Array ( [retval] => [ok] => 1 )
$response= $m->test->execute("return db.foo.count();");
print_r($response); //Array ( [retval] => 3 [ok] => 1 )
$response= $m->test->execute("return db.foo.findOne();");
print_r($response); //Array ( [retval] => Array ( [_id] => MongoId Object ( [$id] => 5287ccbe60e2eac9a0e2f1c6 ) [name] => nanhe [age] => 30 ) [ok] => 1 )
/*
* If you want use find function then use toArray because The find() function returns a cursor, which can't be returned from JavaScript.
*/
$response= $m->test->execute("return db.foo.find().toArray();");
print_r($response); //[$id] => 5287cd2260e2eac9a0e2f1ca ) [name] => happy [age] => 18 ) [2] => Array ( [_id] => MongoId Object ( [$id] => 5287cd2260e2eac9a0e2f1cb ) [name] => prince [age] => 16 ) [3] => Array ( [_id] => MongoId Object ( [$id] => 5287cdea60e2eac9a0e2f1cc ) [name] => nanhe [age] => 30 ) [4] => Array ( [_id] => MongoId Object ( [$id] => 5287cdea60e2eac9a0e2f1cd ) [name] => happy [age] => 18 ) [5] => Array ( [_id] => MongoId Object ( [$id] => 5287cdea60e2eac9a0e2f1ce ) [name] => prince [age] => 16 ) ) [ok] => 1 )
$response= $m->test->execute("return db.foo.find({'name':'nanhe'}).toArray();");
print_r($response); //Array ( [retval] => Array ( [0] => Array ( [_id] => MongoId Object ( [$id] => 5287ce9b60e2eac9a0e2f1d2 ) [name] => nanhe [age] => 30 ) ) [ok] => 1 )
// $id value will be different in your case