Skip to content

Improve pagination execution time #1695

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 31, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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