21
21
use MongoDB \BSON \ObjectID ;
22
22
use MongoDB \BSON \Regex ;
23
23
use MongoDB \BSON \UTCDateTime ;
24
+ use MongoDB \Builder \Accumulator \FirstAccumulator ;
25
+ use MongoDB \Builder \BuilderEncoder ;
26
+ use MongoDB \Builder \Expression \FieldPath ;
27
+ use MongoDB \Builder \Pipeline ;
28
+ use MongoDB \Builder \Stage \GroupStage ;
29
+ use MongoDB \Builder \Stage \LimitStage ;
30
+ use MongoDB \Builder \Stage \MatchStage ;
31
+ use MongoDB \Builder \Stage \ReplaceRootStage ;
32
+ use MongoDB \Builder \Stage \SkipStage ;
33
+ use MongoDB \Builder \Stage \SortStage ;
34
+ use MongoDB \Builder \Variable ;
24
35
use MongoDB \Driver \Cursor ;
25
36
use Override ;
26
37
use RuntimeException ;
@@ -297,6 +308,8 @@ public function toMql(): array
297
308
298
309
$ wheres = $ this ->compileWheres ();
299
310
311
+ $ pipeline = [new MatchStage ($ wheres )];
312
+
300
313
// Use MongoDB's aggregation framework when using grouping or aggregation functions.
301
314
if ($ this ->groups || $ this ->aggregate ) {
302
315
$ group = [];
@@ -409,7 +422,13 @@ public function toMql(): array
409
422
410
423
$ options = $ this ->inheritConnectionOptions ();
411
424
412
- return ['distinct ' => [$ column , $ wheres , $ options ]];
425
+ $ pipeline [] = new GroupStage (
426
+ _id: new FieldPath ($ column ),
427
+ _document: new FirstAccumulator (Variable::root ()),
428
+ );
429
+ $ pipeline [] = new ReplaceRootStage (
430
+ newRoot: new FieldPath ('_document ' ),
431
+ );
413
432
}
414
433
415
434
// Normal query
@@ -429,18 +448,19 @@ public function toMql(): array
429
448
}
430
449
431
450
if ($ this ->orders ) {
432
- $ options [ ' sort ' ] = $ this ->orders ;
451
+ $ pipeline [ ] = new SortStage ( $ this ->orders ) ;
433
452
}
434
453
435
454
if ($ this ->offset ) {
436
- $ options [ ' skip ' ] = $ this ->offset ;
455
+ $ pipeline [ ] = new SkipStage ( $ this ->offset ) ;
437
456
}
438
457
439
458
if ($ this ->limit ) {
440
- $ options [ ' limit ' ] = $ this ->limit ;
459
+ $ pipeline [ ] = new LimitStage ( $ this ->limit ) ;
441
460
}
442
461
443
462
if ($ this ->hint ) {
463
+ // @todo
444
464
$ options ['hint ' ] = $ this ->hint ;
445
465
}
446
466
@@ -458,7 +478,10 @@ public function toMql(): array
458
478
459
479
$ options = $ this ->inheritConnectionOptions ($ options );
460
480
461
- return ['find ' => [$ wheres , $ options ]];
481
+ $ encoder = new BuilderEncoder ();
482
+ $ pipeline = $ encoder ->encode (new Pipeline (...$ pipeline ));
483
+
484
+ return ['aggregate ' => [$ pipeline , $ options ]];
462
485
}
463
486
464
487
/**
0 commit comments