Skip to content

Commit

Permalink
Merge pull request #1695 from josemiguelq/paginating
Browse files Browse the repository at this point in the history
Improve pagination execution time
  • Loading branch information
jenssegers authored Oct 31, 2019
2 parents cdc6e1d + 65a94df commit a8918ac
Showing 1 changed file with 24 additions and 14 deletions.
38 changes: 24 additions & 14 deletions src/Jenssegers/Mongodb/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ public function getFresh($columns = [])
$wheres = $this->compileWheres();

// Use MongoDB's aggregation framework when using grouping or aggregation functions.
if ($this->groups || $this->aggregate || $this->paginating) {
if ($this->groups || $this->aggregate) {
$group = [];
$unwinds = [];

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

// Translate count into sum.
if ($function == 'count') {
// Null coalense only > 7.2

$aggregations = blank($this->aggregate['columns']) ? [] : $this->aggregate['columns'];

if (in_array('*', $aggregations) && $function == 'count') {
// When ORM is paginating, count doesnt need a aggregation, just a cursor operation
// elseif added to use this only in pagination
// https://docs.mongodb.com/manual/reference/method/cursor.count/
// count method returns int

$totalResults = $this->collection->count($wheres);
// Preserving format expected by framework
$results = [
[
'_id' => null,
'aggregate' => $totalResults
]
];
return $this->useCollections ? new Collection($results) : $results;
} elseif ($function == 'count') {
// Translate count into sum.
$group['aggregate'] = ['$sum' => 1];
} // Pass other functions directly.
else {
} else {
$group['aggregate'] = ['$' . $function => '$' . $column];
}
}
}

// When using pagination, we limit the number of returned columns
// by adding a projection.
if ($this->paginating) {
foreach ($this->columns as $column) {
$this->projections[$column] = 1;
}
}


// The _id field is mandatory when using grouping.
if ($group && empty($group['_id'])) {
$group['_id'] = null;
Expand Down

1 comment on commit a8918ac

@LongDinhh
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.