@@ -67,19 +67,22 @@ public function applyToCollection(Builder $aggregationBuilder, string $resourceC
6767 if ($ this ->isPropertyNested ($ field , $ resourceClass )) {
6868 [$ field ] = $ this ->addLookupsForNestedProperty ($ field , $ aggregationBuilder , $ resourceClass , true );
6969 }
70- $ this ->addSort (
71- $ aggregationBuilder ,
72- $ context ['mongodb_odm_sort_fields ' ] = ($ context ['mongodb_odm_sort_fields ' ] ?? []) + [$ field => $ order ]
73- );
70+
71+ $ context ['mongodb_odm_sort_fields ' ] = ($ context ['mongodb_odm_sort_fields ' ] ?? []) + [$ field => $ order ];
72+ if ($ this ->isSearchPipeline ($ aggregationBuilder )) {
73+ $ aggregationBuilder ->getStage (0 )
74+ ->sort ($ context ['mongodb_odm_sort_fields ' ]);
75+ } else {
76+ $ aggregationBuilder ->sort ($ context ['mongodb_odm_sort_fields ' ]);
77+ }
7478 }
7579
7680 return ;
7781 }
7882
79- if (null !== $ this ->order ) {
83+ if (null !== $ this ->order && ! $ this -> isSearchPipeline ( $ aggregationBuilder ) ) {
8084 foreach ($ identifiers as $ identifier ) {
81- $ this ->addSort (
82- $ aggregationBuilder ,
85+ $ aggregationBuilder ->sort (
8386 $ context ['mongodb_odm_sort_fields ' ] = ($ context ['mongodb_odm_sort_fields ' ] ?? []) + [$ identifier => $ this ->order ]
8487 );
8588 }
@@ -91,18 +94,6 @@ protected function getManagerRegistry(): ManagerRegistry
9194 return $ this ->managerRegistry ;
9295 }
9396
94- private function addSort (Builder $ aggregationBuilder , array $ sortFields ): void
95- {
96- $ firstStage = $ aggregationBuilder ->getPipeline (0 );
97- if ($ firstStage instanceof Search) {
98- // The $search stage supports "sort" for performance, it's always first if present
99- $ firstStage ->sort ($ sortFields );
100- } else {
101- // Append a $sort stage at the end of the pipeline
102- $ aggregationBuilder ->sort ($ sortFields );
103- }
104- }
105-
10697 private function hasSortStage (Builder $ aggregationBuilder ): bool
10798 {
10899 try {
@@ -117,4 +108,14 @@ private function hasSortStage(Builder $aggregationBuilder): bool
117108 return false ;
118109 }
119110 }
111+
112+ private function isSearchPipeline (Builder $ aggregationBuilder ): bool
113+ {
114+ try {
115+ return $ aggregationBuilder ->getStage (0 ) instanceof Search;
116+ } catch (\OutOfRangeException ) {
117+ // Empty pipeline
118+ return false ;
119+ }
120+ }
120121}
0 commit comments