MongoCollection::aggregateCursor
(PECL mongo >=1.5.0)
MongoCollection::aggregateCursor — Execute an aggregation pipeline command and retrieve results through a cursor
Описание
With this method you can execute Aggregation Framework pipelines and retrieve the results through a cursor, instead of getting just one document back as you would with MongoCollection::aggregate(). This method returns a MongoCommandCursor object. This cursor object implements the Iterator interface just like the MongoCursor objects that are returned by the MongoCollection::find() method.
Замечание: The resulting MongoCommandCursor will inherit this collection's read preference. MongoCommandCursor::setReadPreference() may be used to change the read preference before iterating on the cursor.
Список параметров
-
pipeline
-
The Aggregation Framework pipeline to execute.
-
options
-
Options for the aggregation command. Valid options include:
-
"allowDiskUse"
Allow aggregation stages to write to temporary files
-
"cursor"
It is possible to configure how many initial documents the server should return with the first result set. The default initial batch size is 101. You can change it by adding the batchSize option:
<?php
$collection->aggregateCursor(
$pipeline,
[ "cursor" => [ "batchSize" => 4 ] ]
);This option only configures the size of the first batch. To configure the size of future batches, please use the MongoCommandCursor::batchSize() method on the returned MongoCommandCursor object.
-
"explain"
Return information on the processing of the pipeline. This option may cause the command to return a result document that is unsuitable for constructing a MongoCommandCursor. If you need to use this option, you should consider using MongoCollection::aggregate().
"maxTimeMS"
Указывает суммарный лимит времени в миллисекундах на обработку операции (не включая время простоя). Если операция не завершилась за это время, то бросается MongoExecutionTimeoutException.
-
Возвращаемые значения
Returns a MongoCommandCursor object. Because this implements the Iterator interface you can iterate over each of the results as returned by the command query. The MongoCommandCursor also implements the MongoCursorInterface interface which adds the MongoCommandCursor::batchSize(), MongoCommandCursor::dead(), MongoCommandCursor::info() methods.
Примеры
Пример #1 MongoCollection::aggregateCursor() example
Finding all of the distinct values for a key.
<?php
$m = new MongoClient;
$db = $m->test;
$people = $db->people;
$people->drop();
$people->insert(array("name" => "Joe", "points" => 4));
$people->insert(array("name" => "Molly", "points" => 43));
$people->insert(array("name" => "Sally", "points" => 22));
$people->insert(array("name" => "Joe", "points" => 22));
$people->insert(array("name" => "Molly", "points" => 87));
$ages = $people->aggregateCursor( [
[ '$group' => [ '_id' => '$name', 'points' => [ '$sum' => '$points' ] ] ],
[ '$sort' => [ 'points' => -1 ] ],
] );
foreach ($ages as $person) {
echo "{$person['_id']}: {$person['points']}\n";
}
?>
Результатом выполнения данного примера будет что-то подобное:
Molly: 130
Joe: 26
Sally: 22
Пример #2 MongoCollection::aggregateCursor() example with different initial batch size
Finding all of the distinct values for a key.
<?php
$m = new MongoClient;
$db = $m->test;
$people = $db->people;
$people->drop();
/* Insert some sample data */
$people->insert(array("name" => "Joe", "points" => 4));
$people->insert(array("name" => "Molly", "points" => 43));
$people->insert(array("name" => "Sally", "points" => 22));
$people->insert(array("name" => "Joe", "points" => 22));
$people->insert(array("name" => "Molly", "points" => 87));
/* Run the command cursor */
$ages = $people->aggregateCursor(
[
[ '$group' => [ '_id' => '$name', 'points' => [ '$sum' => '$points' ] ] ],
[ '$sort' => [ 'points' => -1 ] ],
],
[ "cursor" => [ "batchSize" => 4 ] ]
);
foreach ($ages as $person) {
echo "{$person['_id']}: {$person['points']}\n";
}
?>
Результатом выполнения данного примера будет что-то подобное:
Molly: 130
Joe: 26
Sally: 22
Смотрите также
- MongoDB::command() - Execute a database command
- MongoCommandCursor
- MongoCommandCursor::batchSize() - Limits the number of elements returned in one batch.
- MongoCollection::aggregate() - Perform an aggregation using the aggregation framework
- The MongoDB » aggregation framework
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Расширения для работы с базами данных отдельных производителей
- MongoDB
- Базовые классы
- Функция MongoCollection::aggregate() - Perform an aggregation using the aggregation framework
- Функция MongoCollection::aggregateCursor() - Execute an aggregation pipeline command and retrieve results through a cursor
- Функция MongoCollection::batchInsert() - Inserts multiple documents into this collection
- Функция MongoCollection::__construct() - Creates a new collection
- Функция MongoCollection::count() - Counts the number of documents in this collection
- Функция MongoCollection::createDBRef() - Creates a database reference
- Функция MongoCollection::createIndex() - Creates an index on the specified field(s) if it does not already exist.
- Функция MongoCollection::deleteIndex() - Deletes an index from this collection
- Функция MongoCollection::deleteIndexes() - Delete all indices for this collection
- Функция MongoCollection::distinct() - Retrieve a list of distinct values for the given key across a collection.
- Функция MongoCollection::drop() - Drops this collection
- Функция MongoCollection::ensureIndex() - Creates an index on the specified field(s) if it does not already exist.
- MongoCollection::find
- Функция MongoCollection::findAndModify() - Update a document and return it
- Функция MongoCollection::findOne() - Queries this collection, returning a single element
- Функция MongoCollection::__get() - Gets a collection
- Функция MongoCollection::getDBRef() - Fetches the document pointed to by a database reference
- Функция MongoCollection::getIndexInfo() - Returns information about indexes on this collection
- Функция MongoCollection::getName() - Returns this collection's name
- Функция MongoCollection::getReadPreference() - Get the read preference for this collection
- Функция MongoCollection::getSlaveOkay() - Get slaveOkay setting for this collection
- Функция MongoCollection::getWriteConcern() - Get the write concern for this collection
- Функция MongoCollection::group() - Performs an operation similar to SQL's GROUP BY command
- Функция MongoCollection::insert() - Inserts a document into the collection
- Функция MongoCollection::parallelCollectionScan() - Returns an array of cursors to iterator over a full collection in parallel
- Функция MongoCollection::remove() - Remove records from this collection
- Функция MongoCollection::save() - Saves a document to this collection
- Функция MongoCollection::setReadPreference() - Set the read preference for this collection
- Функция MongoCollection::setSlaveOkay() - Change slaveOkay setting for this collection
- Функция MongoCollection::setWriteConcern() - Set the write concern for this database
- Функция MongoCollection::toIndexString() - Converts keys specifying an index to its identifying string
- Функция MongoCollection::__toString() - String representation of this collection
- Функция MongoCollection::update() - Update records based on a given criteria
- Функция MongoCollection::validate() - Validates this collection
Коментарии
It looks like maxTimeMS option in the latest release (1.5.8) is not valid anymore. Set \MongoCursor::$timeout before you call aggregateCursor()
aggregateCursor with mongoDB 3.6 can cause error:
"the command cursor did not return a correctly structured response"
to fix it on 64 bit systems, temporarily turn on:
ini_set('mongo.long_as_object', true);