12
12
use MongoDB \Builder \BuilderEncoder ;
13
13
use MongoDB \Builder \Expression ;
14
14
use MongoDB \Builder \Type \Sort ;
15
- use MongoDB \Builder \Type \TimeUnit ;
16
- use MongoDB \Builder \Variable ;
17
15
use MongoDB \Laravel \Query \AggregationBuilder ;
18
16
use MongoDB \Laravel \Tests \Models \User ;
19
17
use MongoDB \Laravel \Tests \TestCase ;
20
18
21
- use function assert ;
22
-
23
19
class AggregationBuilderTest extends TestCase
24
20
{
25
21
public function tearDown (): void
@@ -39,16 +35,17 @@ public function testCreateFromQueryBuilder(): void
39
35
->limit (10 )
40
36
->offset (0 )
41
37
->aggregate ();
42
- assert ($ pipeline instanceof AggregationBuilder);
38
+
39
+ $ this ->assertInstanceOf (AggregationBuilder::class, $ pipeline );
40
+
43
41
$ pipeline
44
42
->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 ' ),
49
46
),
50
47
)
51
- ->sort (age : Sort::Desc, name: Sort::Asc)
48
+ ->sort (year : Sort::Desc, name: Sort::Asc)
52
49
->unset ('birthday ' );
53
50
54
51
// The encoder is used to convert the pipeline to a BSON document
@@ -64,30 +61,24 @@ public function testCreateFromQueryBuilder(): void
64
61
['$limit ' => 10 ],
65
62
[
66
63
'$addFields ' => [
67
- 'age ' => [
68
- '$dateDiff ' => [
69
- 'startDate ' => '$birthday ' ,
70
- 'endDate ' => '$$NOW ' ,
71
- 'unit ' => 'year ' ,
72
- ],
73
- ],
64
+ 'year ' => ['$year ' => ['date ' => '$birthday ' ]],
74
65
],
75
66
],
76
- ['$sort ' => ['age ' => -1 , 'name ' => 1 ]],
67
+ ['$sort ' => ['year ' => -1 , 'name ' => 1 ]],
77
68
['$unset ' => ['birthday ' ]],
78
69
],
79
70
])->toCanonicalExtendedJSON ();
80
71
81
72
$ this ->assertJsonStringEqualsJsonString ($ expected , $ json );
82
73
83
- // Execute the pipeline and verify the results
74
+ // Execute the pipeline and validate the results
84
75
$ results = $ pipeline ->get ();
85
76
86
77
$ this ->assertInstanceOf (Collection::class, $ results );
87
78
$ this ->assertCount (1 , $ results );
88
79
$ this ->assertInstanceOf (ObjectId::class, $ results ->first ()['_id ' ]);
89
80
$ this ->assertSame ('John Doe ' , $ results ->first ()['name ' ]);
90
- $ this ->assertIsInt ($ results ->first ()['age ' ]);
81
+ $ this ->assertIsInt ($ results ->first ()['year ' ]);
91
82
$ this ->assertArrayNotHasKey ('birthday ' , $ results ->first ());
92
83
}
93
84
}
0 commit comments