@@ -95,6 +95,49 @@ public function testAddRawStage(): void
9595 $ this ->assertSamePipeline ($ expected , $ pipeline ->getPipeline ());
9696 }
9797
98+ public function testDistinct (): void
99+ {
100+ User::insert ([
101+ ['name ' => 'Jane Doe ' , 'birthday ' => new UTCDateTime (new DateTimeImmutable ('1991-01-01 ' ))],
102+ ['name ' => 'John Doe ' , 'birthday ' => new UTCDateTime (new DateTimeImmutable ('1989-01-01 ' ))],
103+ ['name ' => 'John Doe ' , 'birthday ' => new UTCDateTime (new DateTimeImmutable ('1990-01-01 ' ))],
104+ ]);
105+
106+ // Create the aggregation pipeline from the query builder
107+ $ pipeline = User::orderBy ('name ' )
108+ ->distinct ('name ' )
109+ ->select ('name ' , 'birthday ' )
110+ ->aggregate ();
111+
112+ $ expected = [
113+ [
114+ '$group ' => [
115+ '_id ' => '$name ' ,
116+ '_document ' => ['$first ' => '$$ROOT ' ],
117+ ],
118+ ],
119+ [
120+ '$replaceRoot ' => ['newRoot ' => '$_document ' ],
121+ ],
122+ [
123+ '$sort ' => ['name ' => 1 ],
124+ ],
125+ [
126+ '$project ' => ['birthday ' => true , 'name ' => true ],
127+ ],
128+ ];
129+
130+ $ this ->assertSamePipeline ($ expected , $ pipeline ->getPipeline ());
131+
132+ $ results = $ pipeline ->get ();
133+
134+ $ this ->assertCount (2 , $ results );
135+ $ this ->assertSame ('Jane Doe ' , $ results [0 ]['name ' ]);
136+ $ this ->assertSame ('1991-01-01 ' , $ results [0 ]['birthday ' ]->toDateTime ()->format ('Y-m-d ' ));
137+ $ this ->assertSame ('John Doe ' , $ results [1 ]['name ' ]);
138+ $ this ->assertSame ('1989-01-01 ' , $ results [1 ]['birthday ' ]->toDateTime ()->format ('Y-m-d ' ));
139+ }
140+
98141 private static function assertSamePipeline (array $ expected , Pipeline $ pipeline ): void
99142 {
100143 $ expected = Document::fromPHP (['pipeline ' => $ expected ])->toCanonicalExtendedJSON ();
0 commit comments