@@ -67,19 +67,22 @@ public function applyToCollection(Builder $aggregationBuilder, string $resourceC
67
67
if ($ this ->isPropertyNested ($ field , $ resourceClass )) {
68
68
[$ field ] = $ this ->addLookupsForNestedProperty ($ field , $ aggregationBuilder , $ resourceClass , true );
69
69
}
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
+ }
74
78
}
75
79
76
80
return ;
77
81
}
78
82
79
- if (null !== $ this ->order ) {
83
+ if (null !== $ this ->order && ! $ this -> isSearchPipeline ( $ aggregationBuilder ) ) {
80
84
foreach ($ identifiers as $ identifier ) {
81
- $ this ->addSort (
82
- $ aggregationBuilder ,
85
+ $ aggregationBuilder ->sort (
83
86
$ context ['mongodb_odm_sort_fields ' ] = ($ context ['mongodb_odm_sort_fields ' ] ?? []) + [$ identifier => $ this ->order ]
84
87
);
85
88
}
@@ -91,18 +94,6 @@ protected function getManagerRegistry(): ManagerRegistry
91
94
return $ this ->managerRegistry ;
92
95
}
93
96
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
-
106
97
private function hasSortStage (Builder $ aggregationBuilder ): bool
107
98
{
108
99
try {
@@ -117,4 +108,14 @@ private function hasSortStage(Builder $aggregationBuilder): bool
117
108
return false ;
118
109
}
119
110
}
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
+ }
120
121
}
0 commit comments