@@ -23,6 +23,7 @@ class QueryBuilder
2323 private $ result ;
2424
2525 private $ fields = [];
26+ private $ addFields = [];
2627 private $ limit = 0 ;
2728 private $ skip = 0 ;
2829 private $ count = [];
@@ -114,6 +115,10 @@ public function findAll(): self
114115 $ pipeline [] = $ this ->unwind ;
115116 }
116117
118+ if (!empty ($ this ->addFields )) {
119+ $ pipeline [] = ["\$addFields " => $ this ->addFields ];
120+ }
121+
117122 if (empty (!$ this ->filters )) {
118123 $ pipeline [] = [
119124 "\$match " => $ this ->getNormalizedFilters ()
@@ -164,7 +169,9 @@ public function select($fields): self
164169 }
165170 // ArrayLength Function or COUNT feature
166171 if ($ field instanceof ArrayLength /*|| $field instanceof Count*/ ) {
167- return $ field ->asArray ();
172+ $ arrayLen = $ field ->asArray ();
173+ $ this ->addFields [] = $ arrayLen ;
174+ return [key ($ arrayLen ) => 1 ];
168175 }
169176 return $ field ;
170177 }, $ fields );
@@ -182,6 +189,10 @@ public function select($fields): self
182189 $ this ->fields = call_user_func_array ("array_merge " , $ this ->fields );
183190 }
184191
192+ if (count ($ this ->addFields )) {
193+ $ this ->addFields = call_user_func_array ("array_merge " , $ this ->addFields );
194+ }
195+
185196 // Exclude built in _id if not set in fields - MongoDB always returns this by default
186197 if (!in_array ("_id " , $ fields )) {
187198 $ this ->fields ["_id " ] = 0 ;
0 commit comments