AggregateFunctionalTest.php 2.08 KB
Newer Older
1 2 3 4 5
<?php

namespace MongoDB\Tests\Collection\CrudSpec;

use MongoDB\Collection;
6 7
use MongoDB\FeatureDetection;
use MongoDB\Driver\ReadPreference;
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

/**
 * CRUD spec functional tests for aggregate().
 *
 * @see https://github.com/mongodb/specifications/tree/master/source/crud/tests
 */
class AggregateFunctionalTest extends FunctionalTestCase
{
    public function setUp()
    {
        parent::setUp();

        $this->createFixtures(3);
    }

    public function testAggregateWithMultipleStages()
    {
        $cursor = $this->collection->aggregate(
            array(
                array('$sort' => array('x' => 1)),
                array('$match' => array('_id' => array('$gt' => 1))),
            ),
            array('batchSize' => 2)
        );

        $expected = array(
            array('_id' => 2, 'x' => 22),
            array('_id' => 3, 'x' => 33),
        );

38 39
        // Use iterator_to_array() here since aggregate() may return an ArrayIterator
        $this->assertSame($expected, iterator_to_array($cursor));
40 41 42 43
    }

    public function testAggregateWithOut()
    {
44 45 46 47 48 49
        $server = $this->manager->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY));

        if ( ! FeatureDetection::isSupported($server, FeatureDetection::API_AGGREGATE_CURSOR)) {
            $this->markTestSkipped('$out aggregation pipeline operator is not supported');
        }

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
        $outputCollection = new Collection($this->manager, $this->getNamespace() . '_output');
        $this->dropCollectionIfItExists($outputCollection);

        $this->collection->aggregate(
            array(
                array('$sort' => array('x' => 1)),
                array('$match' => array('_id' => array('$gt' => 1))),
                array('$out' => $outputCollection->getCollectionName()),
            )
        );

        $expected = array(
            array('_id' => 2, 'x' => 22),
            array('_id' => 3, 'x' => 33),
        );

        $this->assertSame($expected, $outputCollection->find()->toArray());
67 68 69

        // Manually clean up our output collection
        $this->dropCollectionIfItExists($outputCollection);
70 71
    }
}