@@ -232,7 +232,7 @@ public function getFresh($columns = [])
232
232
$ wheres = $ this ->compileWheres ();
233
233
234
234
// Use MongoDB's aggregation framework when using grouping or aggregation functions.
235
- if ($ this ->groups || $ this ->aggregate || $ this -> paginating ) {
235
+ if ($ this ->groups || $ this ->aggregate ) {
236
236
$ group = [];
237
237
$ unwinds = [];
238
238
@@ -267,24 +267,34 @@ public function getFresh($columns = [])
267
267
$ column = implode ('. ' , $ splitColumns );
268
268
}
269
269
270
- // Translate count into sum.
271
- if ($ function == 'count ' ) {
270
+ // Null coalense only > 7.2
271
+
272
+ $ aggregations = blank ($ this ->aggregate ['columns ' ]) ? [] : $ this ->aggregate ['columns ' ];
273
+
274
+ if (in_array ('* ' , $ aggregations ) && $ function == 'count ' ) {
275
+ // When ORM is paginating, count doesnt need a aggregation, just a cursor operation
276
+ // elseif added to use this only in pagination
277
+ // https://docs.mongodb.com/manual/reference/method/cursor.count/
278
+ // count method returns int
279
+
280
+ $ totalResults = $ this ->collection ->count ($ wheres );
281
+ // Preserving format expected by framework
282
+ $ results = [
283
+ [
284
+ '_id ' => null ,
285
+ 'aggregate ' => $ totalResults
286
+ ]
287
+ ];
288
+ return $ this ->useCollections ? new Collection ($ results ) : $ results ;
289
+ } elseif ($ function == 'count ' ) {
290
+ // Translate count into sum.
272
291
$ group ['aggregate ' ] = ['$sum ' => 1 ];
273
- } // Pass other functions directly.
274
- else {
292
+ } else {
275
293
$ group ['aggregate ' ] = ['$ ' . $ function => '$ ' . $ column ];
276
294
}
277
295
}
278
296
}
279
-
280
- // When using pagination, we limit the number of returned columns
281
- // by adding a projection.
282
- if ($ this ->paginating ) {
283
- foreach ($ this ->columns as $ column ) {
284
- $ this ->projections [$ column ] = 1 ;
285
- }
286
- }
287
-
297
+
288
298
// The _id field is mandatory when using grouping.
289
299
if ($ group && empty ($ group ['_id ' ])) {
290
300
$ group ['_id ' ] = null ;
1 commit comments
LongDinhh commentedon Nov 1, 2019
To calculate totals and return a subset, you need to apply grouping and skip/limit to the same dataset. For that you can utilise facets