Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

query the collection to improve performance #2589

Answered by GromNaN
nemesisKO asked this question in General
Discussion options

I want get filtered collection between to date and store it into some variable. then use this variable into another functions to group by and ... for avoiding each function filtered entire collection by date and group by. my code is

$result = $query->whereRaw([
 '$and' =>
 $searchArray
 ]
);
$groupByResults = $result->raw(function ($collection) {
 return $collection->aggregate([
 [
 '$group' => [
 "_id" => ['$substr' => ['$hs_code', 0, 2]],
 "success_num" => ['$sum' => '$total_value_usd'],
 ],
 ],
 [
 '$sort' => [
 "success_num" => -1,
 ],
 ],
 [
 '$facet' => [
 "data" => [['$skip' => 0 * 10], ['$limit' => 10]],
 ],
 ],
 ]);
});

and the $groupByResult get entire collection and groupBy and ignore first $result query. do you know how to fix it?

You must be logged in to vote

You cannot use Query\Builder::raw(Closure) with other methods of the query builder.

Try moving the where part into a $match stage.

$groupByResults = $result->raw(function ($collection) {
 return $collection->aggregate([
 [
 '$match' => $searchArray,
 ],
 [
 '$group' => [
 "_id" => ['$substr' => ['$hs_code', 0, 2]],
 "success_num" => ['$sum' => '$total_value_usd'],
 ],
 ],
 [
 '$sort' => [
 "success_num" => -1,
 ],
 ],
 [
 '$facet' => [
 "data" => [['$skip' => 0 * 10], ['$limit' => 10]],
 ],
 ],
 ...

Replies: 1 comment

Comment options

You cannot use Query\Builder::raw(Closure) with other methods of the query builder.

Try moving the where part into a $match stage.

$groupByResults = $result->raw(function ($collection) {
 return $collection->aggregate([
 [
 '$match' => $searchArray,
 ],
 [
 '$group' => [
 "_id" => ['$substr' => ['$hs_code', 0, 2]],
 "success_num" => ['$sum' => '$total_value_usd'],
 ],
 ],
 [
 '$sort' => [
 "success_num" => -1,
 ],
 ],
 [
 '$facet' => [
 "data" => [['$skip' => 0 * 10], ['$limit' => 10]],
 ],
 ],
 ]);
});
You must be logged in to vote
0 replies
Answer selected by GromNaN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Converted from issue

This discussion was converted from issue #2540 on August 31, 2023 14:57.

AltStyle によって変換されたページ (->オリジナル) /