Skip to content

Commit 01cfc1a

Browse files
committed
Update aggregation example for mongodb 4.4 support
1 parent 52cf3d3 commit 01cfc1a

File tree

1 file changed

+11
-20
lines changed

1 file changed

+11
-20
lines changed

tests/Query/AggregationBuilderTest.php

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,10 @@
1212
use MongoDB\Builder\BuilderEncoder;
1313
use MongoDB\Builder\Expression;
1414
use MongoDB\Builder\Type\Sort;
15-
use MongoDB\Builder\Type\TimeUnit;
16-
use MongoDB\Builder\Variable;
1715
use MongoDB\Laravel\Query\AggregationBuilder;
1816
use MongoDB\Laravel\Tests\Models\User;
1917
use MongoDB\Laravel\Tests\TestCase;
2018

21-
use function assert;
22-
2319
class AggregationBuilderTest extends TestCase
2420
{
2521
public function tearDown(): void
@@ -39,16 +35,17 @@ public function testCreateFromQueryBuilder(): void
3935
->limit(10)
4036
->offset(0)
4137
->aggregate();
42-
assert($pipeline instanceof AggregationBuilder);
38+
39+
$this->assertInstanceOf(AggregationBuilder::class, $pipeline);
40+
4341
$pipeline
4442
->addFields(
45-
age: Expression::dateDiff(
46-
startDate: Expression::dateFieldPath('birthday'),
47-
endDate: Variable::now(),
48-
unit: TimeUnit::Year,
43+
// Requires MongoDB 5.0+
44+
year: Expression::year(
45+
Expression::dateFieldPath('birthday'),
4946
),
5047
)
51-
->sort(age: Sort::Desc, name: Sort::Asc)
48+
->sort(year: Sort::Desc, name: Sort::Asc)
5249
->unset('birthday');
5350

5451
// The encoder is used to convert the pipeline to a BSON document
@@ -64,30 +61,24 @@ public function testCreateFromQueryBuilder(): void
6461
['$limit' => 10],
6562
[
6663
'$addFields' => [
67-
'age' => [
68-
'$dateDiff' => [
69-
'startDate' => '$birthday',
70-
'endDate' => '$$NOW',
71-
'unit' => 'year',
72-
],
73-
],
64+
'year' => ['$year' => ['date' => '$birthday']],
7465
],
7566
],
76-
['$sort' => ['age' => -1, 'name' => 1]],
67+
['$sort' => ['year' => -1, 'name' => 1]],
7768
['$unset' => ['birthday']],
7869
],
7970
])->toCanonicalExtendedJSON();
8071

8172
$this->assertJsonStringEqualsJsonString($expected, $json);
8273

83-
// Execute the pipeline and verify the results
74+
// Execute the pipeline and validate the results
8475
$results = $pipeline->get();
8576

8677
$this->assertInstanceOf(Collection::class, $results);
8778
$this->assertCount(1, $results);
8879
$this->assertInstanceOf(ObjectId::class, $results->first()['_id']);
8980
$this->assertSame('John Doe', $results->first()['name']);
90-
$this->assertIsInt($results->first()['age']);
81+
$this->assertIsInt($results->first()['year']);
9182
$this->assertArrayNotHasKey('birthday', $results->first());
9283
}
9384
}

0 commit comments

Comments
 (0)