Skip to content

Commit 06da294

Browse files
committed
Add tests on distinct
1 parent fde7ad2 commit 06da294

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

src/Query/Builder.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -600,7 +600,7 @@ public function generateCacheKey()
600600
public function aggregate($function = null, $columns = [])
601601
{
602602
if ($function === null) {
603-
if ($columns !== []) {
603+
if ($columns !== [] && $columns !== ['*']) {
604604
throw new InvalidArgumentException('Columns cannot be specified to create an aggregation builder. Add a $project stage instead.');
605605
}
606606

tests/Query/AggregationBuilderTest.php

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)