Skip to content

Commit a8918ac

Browse files
authoredOct 31, 2019
Merge pull request #1695 from josemiguelq/paginating
Improve pagination execution time
2 parents cdc6e1d + 65a94df commit a8918ac

File tree

1 file changed

+24
-14
lines changed

1 file changed

+24
-14
lines changed
 

‎src/Jenssegers/Mongodb/Query/Builder.php

+24-14
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ public function getFresh($columns = [])
232232
$wheres = $this->compileWheres();
233233

234234
// 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) {
236236
$group = [];
237237
$unwinds = [];
238238

@@ -267,24 +267,34 @@ public function getFresh($columns = [])
267267
$column = implode('.', $splitColumns);
268268
}
269269

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.
272291
$group['aggregate'] = ['$sum' => 1];
273-
} // Pass other functions directly.
274-
else {
292+
} else {
275293
$group['aggregate'] = ['$' . $function => '$' . $column];
276294
}
277295
}
278296
}
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+
288298
// The _id field is mandatory when using grouping.
289299
if ($group && empty($group['_id'])) {
290300
$group['_id'] = null;

1 commit comments

Comments
 (1)

LongDinhh commented on Nov 1, 2019

@LongDinhh

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

Please sign in to comment.