MongoDB::command
(PECL mongo >=0.9.2)
MongoDB::command — Execute a database command
Описание
$command
[, array $options
= array()
] )Almost everything that is not a CRUD operation can be done with a database command. Need to know the database version? There's a command for that. Need to do aggregation? There's a command for that. Need to turn up logging? You get the idea.
This method is identical to:
<?php
public function command($data) {
return $this->selectCollection('$cmd')->findOne($data);
}
?>
Список параметров
-
command
-
The query to send.
-
options
-
This parameter is an associative array of the form array("optionname" => <boolean>, ...). Currently supported options are:
"timeout"
Целое значение, по умолчанию равно MongoCursor::$timeout. Если используются подтвержденные операции записи, то значение обозначает количество миллисекунд, в течение которого клиент будет ожидать ответа от базы данных. Если база данных не ответит в течение указанного периода, то будет брошено исключение MongoCursorTimeoutException.
Список изменений
Версия | Описание |
---|---|
1.2.0 | Added options parameter with a single option: "timeout". |
Возвращаемые значения
Returns database response. Every database response is always maximum one document, which means that the result of a database command can never exceed 16MB. The resulting document's structure depends on the command, but most results will have the ok field to indicate success or failure and results containing an array of each of the resulting documents.
Примеры
Пример #1 MongoDB::command() "distinct" example
Finding all of the distinct values for a key.
<?php
$people = $db->people;
$people->insert(array("name" => "Joe", "age" => 4));
$people->insert(array("name" => "Sally", "age" => 22));
$people->insert(array("name" => "Dave", "age" => 22));
$people->insert(array("name" => "Molly", "age" => 87));
$ages = $db->command(array("distinct" => "people", "key" => "age"));
foreach ($ages['values'] as $age) {
echo "$age\n";
}
?>
Результатом выполнения данного примера будет что-то подобное:
4
22
87
Пример #2 MongoDB::command() "distinct" example
Finding all of the distinct values for a key, where the value is larger than or equal to 18.
<?php
$people = $db->people;
$people->insert(array("name" => "Joe", "age" => 4));
$people->insert(array("name" => "Sally", "age" => 22));
$people->insert(array("name" => "Dave", "age" => 22));
$people->insert(array("name" => "Molly", "age" => 87));
$ages = $db->command(
array(
"distinct" => "people",
"key" => "age",
"query" => array("age" => array('$gte' => 18))
)
);
foreach ($ages['values'] as $age) {
echo "$age\n";
}
?>
Результатом выполнения данного примера будет что-то подобное:
22
87
Пример #3 MongoDB::command() MapReduce example
Get all users with at least on "sale" event, and how many times each of these users has had a sale.
<?php
// sample event document
$events->insert(array("user_id" => $id,
"type" => $type,
"time" => new MongoDate(),
"desc" => $description));
// construct map and reduce functions
$map = new MongoCode("function() { emit(this.user_id,1); }");
$reduce = new MongoCode("function(k, vals) { ".
"var sum = 0;".
"for (var i in vals) {".
"sum += vals[i];".
"}".
"return sum; }");
$sales = $db->command(array(
"mapreduce" => "events",
"map" => $map,
"reduce" => $reduce,
"query" => array("type" => "sale"),
"out" => array("merge" => "eventCounts")));
$users = $db->selectCollection($sales['result'])->find();
foreach ($users as $user) {
echo "{$user['_id']} had {$user['value']} sale(s).\n";
}
?>
Результатом выполнения данного примера будет что-то подобное:
User 47cc67093475061e3d9536d2 had 3 sale(s).
User 49902cde5162504500b45c2c had 14 sale(s).
User 4af467e4fd543cce7b0ea8e2 had 1 sale(s).
Замечание: Using MongoCode
This example uses MongoCode, which can also take a scope argument. However, at the moment, MongoDB does not support using scopes in MapReduce. If you would like to use client-side variables in the MapReduce functions, you can add them to the global scope by using the optional scope field with the database command. See the » MapReduce documentation for more information.
Замечание: The out argument
Before 1.8.0, the out argument was optional. If you did not use it, MapReduce results would be written to a temporary collection, which would be deleted when your connection was closed. In 1.8.0+, the out argument is required. See the » MapReduce documentation for more information.
If you are going to be using MapReduce, Prajwal Tuladhar created an API for Mongo PHP users which provides a nicer interface than the bare command. You can download it from » Github and there is a » blog post on how to use it.
Пример #4 MongoDB::command() "textSearch" example
Do a fulltext search lookup with MongoDB's 2.4 and higher "text search" functionality.
<?php
$m = new MongoClient();
$d = $m->demo;
$c = $d->planets;
$c->insert(array("name" => "Mercury", "desc" => "Mercury is the smallest and closest to the Sun"));
$c->insert(array("name" => "Venus", "desc" => "Venus is the second planet from the Sun, orbiting it every 224.7 Earth days."));
$c->insert(array("name" => "Earth", "desc" => "Earth is the the densest of the eight planets in the Solar System."));
$c->insert(array("name" => "Mars", "desc" => "Mars is named after the Roman god of war."));
$c->ensureIndex(array('desc' => 'text'));
$r = $d->command(array("text" => "planets", 'search' => "sun" ));
print_r($r);
?>
Результатом выполнения данного примера будет что-то подобное:
Array
(
[queryDebugString] => sun||||||
[language] => english
[results] => Array
(
[0] => Array
(
[score] => 0.625
[obj] => Array
(
[_id] => MongoId Object
(
[$id] => 517549d944670a4a5cb3059a
)
[name] => Mercury
[desc] => Mercury is the smallest and closest to the Sun
)
)
[1] => Array
(
[score] => 0.55
[obj] => Array
(
[_id] => MongoId Object
(
[$id] => 517549d944670a4a5cb3059b
)
[name] => Venus
[desc] => Venus is the second planet from the Sun, orbiting it every 224.7 Earth days.
)
)
)
[stats] => Array
(
[nscanned] => 2
[nscannedObjects] => 0
[n] => 2
[nfound] => 2
[timeMicros] => 95
)
[ok] => 1
)
Пример #5 MongoDB::command() "geoNear" example
This example shows how to use the geoNear command.
<?php
$m = new MongoClient();
$d = $m->demo;
$c = $d->poiConcat;
$r = $d->command(array(
'geoNear' => "poiConcat", // Search in the poiConcat collection
'near' => array(-0.08, 51.48), // Search near 51.48°N, 0.08°E
'spherical' => true, // Enable spherical search
'num' => 5, // Maximum 5 returned documents
));
print_r($r);
?>
Смотрите также
- MongoCollection::aggregate() - Perform an aggregation using the aggregation framework
- MongoCollection::findAndModify() - Update a document and return it
- MongoCollection::group() - Performs an operation similar to SQL's GROUP BY command
MongoDB core docs on » database commands and on individual commands: » findAndModify, » getLastError, and » repairDatabase (dozens more exist, there are merely a few examples).
- 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
Коментарии
rename a collection:
<?php
$m = new Mongo();
$adminDB = $m->admin; //require admin priviledge
//rename collection 'colA' in db 'yourdbA' to collection 'colB' in another db 'yourdbB'
$res = $adminDB->command(array(
"renameCollection" => "yourdbA.colA",
"to" => "yourdbB.colB"
));
var_dump($res);
?>
I tried to write MapReduce. Unfortunately, out => array('replace' => 'collName') did not work for me. Instead, the below code works
<?php
$mongo->command(array(
'mapreduce' => 'events',
'map' => $map,
'reduce' => $reduce,
'out' => 'mapReduceEventStats'
));
?>
> Need to know the database version? There's a command for that.
We didn't find it - ended up using either;
<?php
$m = new Mongo();
$adminDB = $m->admin; //require admin priviledge
$mongodb_info = $adminDB->command(array('buildinfo'=>true));
$mongodb_version = $mongodb_info['version'];
print_r($mongodb_info);
?>
or
<?php
$v = `mongo --version`;
print_r($v);
?>
Command of Mongo 2.4 Text Search feature.
<?php
$result = $db->command(
array(
'text' => 'bar', //this is the name of the collection where we are searching
'search' => 'hotel', //the string to search
'limit' => 5, //the number of results, by default is 1000
'project' => Array( //the fields to retrieve from db
'title' => 1
)
)
);
$db=new new Mongo();
Copy old_db to new_db
$responseCopy = $db->admin->command(array(
'copydb' => 1,
'fromhost' => 'localhost',
'fromdb' => 'old_db',
'todb' =>'new_db'
));
Now drop old_db
if($responseCopy['ok']==1){
$responseDrop=$db->old_db->command(array('dropDatabase' => 1));
//OR
$responseDrop =$db->old_db->drop();
}
Show Output
print_r($responseCopy);
print_r($responseDrop);
Output will be something like this
Array ( [ok] => 1 )
Array ( [dropped] => old_db [ok] => 1 )