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

namespace MongoDB\Tests\Operation;

5
use MongoDB\Collection;
6
use MongoDB\Driver\BulkWrite;
7
use MongoDB\Driver\ReadPreference;
8
use MongoDB\Driver\WriteConcern;
9
use MongoDB\Driver\Exception\RuntimeException;
10
use MongoDB\Operation\Aggregate;
11
use MongoDB\Tests\CommandObserver;
12
use ArrayIterator;
13
use Exception;
14
use stdClass;
15 16 17

class AggregateFunctionalTest extends FunctionalTestCase
{
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
    public function testBatchSizeIsIgnoredIfPipelineIncludesOutStage()
    {
        (new CommandObserver)->observe(
            function() {
                $operation = new Aggregate(
                    $this->getDatabaseName(),
                    $this->getCollectionName(),
                    [['$out' => $this->getCollectionName() . '.output']],
                    ['batchSize' => 0]
                );

                $operation->execute($this->getPrimaryServer());
            },
            function(array $event) {
                $this->assertEquals(new stdClass, $event['started']->getCommand()->cursor);
            }
        );

        $outCollection = new Collection($this->manager, $this->getDatabaseName(), $this->getCollectionName() . '.output');
        $outCollection->drop();
    }

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
    public function testCurrentOpCommand()
    {
        if (version_compare($this->getServerVersion(), '3.6.0', '<')) {
            $this->markTestSkipped('$currentOp is not supported');
        }

        (new CommandObserver)->observe(
            function() {
                $operation = new Aggregate(
                    'admin',
                    null,
                    [['$currentOp' => (object) []]]
                );

                $operation->execute($this->getPrimaryServer());
            },
56 57
            function(array $event) {
                $this->assertSame(1, $event['started']->getCommand()->aggregate);
58 59 60 61
            }
        );
    }

62 63 64 65 66 67 68 69 70 71 72 73 74
    public function testDefaultReadConcernIsOmitted()
    {
        (new CommandObserver)->observe(
            function() {
                $operation = new Aggregate(
                    $this->getDatabaseName(),
                    $this->getCollectionName(),
                    [['$match' => ['x' => 1]]],
                    ['readConcern' => $this->createDefaultReadConcern()]
                );

                $operation->execute($this->getPrimaryServer());
            },
75 76
            function(array $event) {
                $this->assertObjectNotHasAttribute('readConcern', $event['started']->getCommand());
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
            }
        );
    }

    public function testDefaultWriteConcernIsOmitted()
    {
        (new CommandObserver)->observe(
            function() {
                $operation = new Aggregate(
                    $this->getDatabaseName(),
                    $this->getCollectionName(),
                    [['$out' => $this->getCollectionName() . '.output']],
                    ['writeConcern' => $this->createDefaultWriteConcern()]
                );

                $operation->execute($this->getPrimaryServer());
            },
94 95
            function(array $event) {
                $this->assertObjectNotHasAttribute('writeConcern', $event['started']->getCommand());
96 97
            }
        );
98 99 100

        $outCollection = new Collection($this->manager, $this->getDatabaseName(), $this->getCollectionName() . '.output');
        $outCollection->drop();
101 102
    }

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    public function testEmptyPipelineReturnsAllDocuments()
    {
        $this->createFixtures(3);

        $operation = new Aggregate($this->getDatabaseName(), $this->getCollectionName(), []);
        $results = iterator_to_array($operation->execute($this->getPrimaryServer()));

        $expectedDocuments = [
            (object) ['_id' => 1, 'x' => (object) ['foo' => 'bar']],
            (object) ['_id' => 2, 'x' => (object) ['foo' => 'bar']],
            (object) ['_id' => 3, 'x' => (object) ['foo' => 'bar']],
        ];

        $this->assertEquals($expectedDocuments, $results);
    }

119 120 121
    public function testUnrecognizedPipelineState()
    {
        $operation = new Aggregate($this->getDatabaseName(), $this->getCollectionName(), [['$foo' => 1]]);
122
        $this->expectException(RuntimeException::class);
123 124 125
        $operation->execute($this->getPrimaryServer());
    }

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
    public function testSessionOption()
    {
        if (version_compare($this->getServerVersion(), '3.6.0', '<')) {
            $this->markTestSkipped('Sessions are not supported');
        }

        (new CommandObserver)->observe(
            function() {
                $operation = new Aggregate(
                    $this->getDatabaseName(),
                    $this->getCollectionName(),
                    [],
                    ['session' => $this->createSession()]
                );

                $operation->execute($this->getPrimaryServer());
            },
143 144
            function(array $event) {
                $this->assertObjectHasAttribute('lsid', $event['started']->getCommand());
145 146 147 148
            }
        );
    }

149
    /**
150
     * @dataProvider provideTypeMapOptionsAndExpectedDocuments
151
     */
152
    public function testTypeMapOption(array $typeMap = null, array $expectedDocuments)
153 154 155 156
    {
        $this->createFixtures(3);

        $pipeline = [['$match' => ['_id' => ['$ne' => 2]]]];
157

158
        $operation = new Aggregate($this->getDatabaseName(), $this->getCollectionName(), $pipeline, ['typeMap' => $typeMap]);
159
        $results = iterator_to_array($operation->execute($this->getPrimaryServer()));
160

161
        $this->assertEquals($expectedDocuments, $results);
162 163
    }

164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    /**
     * @dataProvider provideTypeMapOptionsAndExpectedDocuments
     */
    public function testTypeMapOptionWithoutCursor(array $typeMap = null, array $expectedDocuments)
    {
        if (version_compare($this->getServerVersion(), '3.6.0', '>=')) {
            $this->markTestSkipped('Aggregations with useCursor == false are not supported');
        }

        $this->createFixtures(3);

        $pipeline = [['$match' => ['_id' => ['$ne' => 2]]]];

        $operation = new Aggregate($this->getDatabaseName(), $this->getCollectionName(), $pipeline, ['typeMap' => $typeMap, 'useCursor' => false]);
        $results = $operation->execute($this->getPrimaryServer());

        $this->assertInstanceOf(ArrayIterator::class, $results);
        $this->assertEquals($expectedDocuments, iterator_to_array($results));
    }

184 185 186 187 188 189 190 191 192
    public function testExplainOption()
    {
        $this->createFixtures(3);

        $pipeline = [['$match' => ['_id' => ['$ne' => 2]]]];
        $operation = new Aggregate($this->getDatabaseName(), $this->getCollectionName(), $pipeline, ['explain' => true, 'typeMap' => ['root' => 'array']]);
        $results = iterator_to_array($operation->execute($this->getPrimaryServer()));

        $this->assertCount(1, $results);
193 194 195 196 197 198 199

        /* MongoDB 4.2 may optimize aggregate pipelines into queries, which can
         * result in different explain output (see: SERVER-24860) */
        $this->assertThat($results[0], $this->logicalOr(
            $this->arrayHasKey('stages'),
            $this->arrayHasKey('queryPlanner')
        ));
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    }

    public function testExplainOptionWithWriteConcern()
    {
        if (version_compare($this->getServerVersion(), '3.4.0', '<')) {
            $this->markTestSkipped('The writeConcern option is not supported');
       }

        $this->createFixtures(3);

        $pipeline = [['$match' => ['_id' => ['$ne' => 2]]], ['$out' => $this->getCollectionName() . '.output']];
        $options = ['explain' => true, 'writeConcern' => new WriteConcern(1)];

        (new CommandObserver)->observe(
            function() use ($pipeline, $options) {
                $operation = new Aggregate($this->getDatabaseName(), $this->getCollectionName(), $pipeline, $options);

                $results = iterator_to_array($operation->execute($this->getPrimaryServer()));

                $this->assertCount(1, $results);
                $this->assertObjectHasAttribute('stages', current($results));
            },
222 223
            function(array $event) {
                $this->assertObjectNotHasAttribute('writeConcern', $event['started']->getCommand());
224 225 226 227 228 229
            }
        );

        $this->assertCollectionCount($this->getCollectionName() . '.output', 0);
    }

230 231
    public function testBypassDocumentValidationSetWhenTrue()
    {
232 233 234 235
        if (version_compare($this->getServerVersion(), '3.2.0', '<')) {
            $this->markTestSkipped('bypassDocumentValidation is not supported');
        }

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
        (new CommandObserver)->observe(
            function() {
                $operation = new Aggregate(
                    $this->getDatabaseName(),
                    $this->getCollectionName(),
                    [['$match' => ['x' => 1]]],
                    ['bypassDocumentValidation' => true]
                );

                $operation->execute($this->getPrimaryServer());
            },
            function(array $event) {
                $this->assertObjectHasAttribute('bypassDocumentValidation', $event['started']->getCommand());
                $this->assertEquals(true, $event['started']->getCommand()->bypassDocumentValidation);
            }
        );
    }

    public function testBypassDocumentValidationUnsetWhenFalse()
    {
256 257 258 259
        if (version_compare($this->getServerVersion(), '3.2.0', '<')) {
            $this->markTestSkipped('bypassDocumentValidation is not supported');
        }

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        (new CommandObserver)->observe(
            function() {
                $operation = new Aggregate(
                    $this->getDatabaseName(),
                    $this->getCollectionName(),
                    [['$match' => ['x' => 1]]],
                    ['bypassDocumentValidation' => false]
                );

                $operation->execute($this->getPrimaryServer());
            },
            function(array $event) {
                $this->assertObjectNotHasAttribute('bypassDocumentValidation', $event['started']->getCommand());
            }
        );
    }

277
    public function provideTypeMapOptionsAndExpectedDocuments()
278 279
    {
        return [
280 281 282 283 284 285 286
            [
                null,
                [
                    (object) ['_id' => 1, 'x' => (object) ['foo' => 'bar']],
                    (object) ['_id' => 3, 'x' => (object) ['foo' => 'bar']],
                ],
            ],
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
            [
                ['root' => 'array', 'document' => 'array'],
                [
                    ['_id' => 1, 'x' => ['foo' => 'bar']],
                    ['_id' => 3, 'x' => ['foo' => 'bar']],
                ],
            ],
            [
                ['root' => 'object', 'document' => 'array'],
                [
                    (object) ['_id' => 1, 'x' => ['foo' => 'bar']],
                    (object) ['_id' => 3, 'x' => ['foo' => 'bar']],
                ],
            ],
            [
                ['root' => 'array', 'document' => 'stdClass'],
                [
                    ['_id' => 1, 'x' => (object) ['foo' => 'bar']],
                    ['_id' => 3, 'x' => (object) ['foo' => 'bar']],
                ],
            ],
        ];
    }

311 312 313 314 315
    public function testReadPreferenceWithinTransaction()
    {
        $this->skipIfTransactionsAreNotSupported();

        // Collection must be created before the transaction starts
316
        $this->createCollection();
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345

        $session = $this->manager->startSession();
        $session->startTransaction();

        try {
            $this->createFixtures(3, ['session' => $session]);

            $pipeline = [['$match' => ['_id' => ['$lt' => 3]]]];
            $options = [
                'readPreference' => new ReadPreference('primary'),
                'session' => $session,
            ];

            $operation = new Aggregate($this->getDatabaseName(), $this->getCollectionName(), $pipeline, $options);
            $cursor = $operation->execute($this->getPrimaryServer());

            $expected = [
                ['_id' => 1, 'x' => ['foo' => 'bar']],
                ['_id' => 2, 'x' => ['foo' => 'bar']],
            ];

            $this->assertSameDocuments($expected, $cursor);

            $session->commitTransaction();
        } finally {
            $session->endSession();
        }
    }

346 347 348 349
    /**
     * Create data fixtures.
     *
     * @param integer $n
350
     * @param array   $executeBulkWriteOptions
351
     */
352
    private function createFixtures($n, array $executeBulkWriteOptions = [])
353 354 355 356 357 358 359 360 361 362
    {
        $bulkWrite = new BulkWrite(['ordered' => true]);

        for ($i = 1; $i <= $n; $i++) {
            $bulkWrite->insert([
                '_id' => $i,
                'x' => (object) ['foo' => 'bar'],
            ]);
        }

363
        $result = $this->manager->executeBulkWrite($this->getNamespace(), $bulkWrite, $executeBulkWriteOptions);
364 365

        $this->assertEquals($n, $result->getInsertedCount());
366 367
    }
}