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

namespace MongoDB\Tests\Collection\CrudSpec;

use MongoDB\Collection;
6
use MongoDB\Driver\ReadPreference;
7
use MongoDB\Operation\DropCollection;
8 9 10 11 12 13 14 15

/**
 * CRUD spec functional tests for aggregate().
 *
 * @see https://github.com/mongodb/specifications/tree/master/source/crud/tests
 */
class AggregateFunctionalTest extends FunctionalTestCase
{
16 17
    private static $wireVersionForOutOperator = 2;

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
    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(
36 37
            array('_id' => 2, 'x' => 22),
            array('_id' => 3, 'x' => 33),
38 39
        );

40
        $this->assertSameDocuments($expected, $cursor);
41 42 43 44
    }

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

47
        if ( ! \MongoDB\server_supports_feature($server, self::$wireVersionForOutOperator)) {
48 49 50
            $this->markTestSkipped('$out aggregation pipeline operator is not supported');
        }

51
        $outputCollection = new Collection($this->manager, $this->getNamespace() . '_output');
52 53
        $operation = new DropCollection($this->getDatabaseName(), $outputCollection->getCollectionName());
        $operation->execute($this->getPrimaryServer());
54 55 56 57 58 59 60 61 62 63 64 65 66 67

        $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),
        );

68
        $this->assertSameDocuments($expected, $outputCollection->find());
69 70

        // Manually clean up our output collection
71 72
        $operation = new DropCollection($this->getDatabaseName(), $outputCollection->getCollectionName());
        $operation->execute($this->getPrimaryServer());
73 74
    }
}