{"record":{"id":"6cf9efd65311d37f","repo":"mongodb/laravel-mongodb","slug":"ordering-by-the-aggregated-field-s-is-not-supported-as-it-is","errorCode":null,"errorMessage":"Ordering by the aggregated field \"%s\" is not supported, as it is computed after the documents are read. Sort the results with the collection method \"sortBy\" instead.","messagePattern":"Ordering by the aggregated field \"(.+?)\" is not supported, as it is computed after the documents are read\\. Sort the results with the collection method \"sortBy\" instead\\.","errorType":"exception","errorClass":"LogicException","httpStatus":null,"severity":"error","filePath":"src/Helpers/QueriesRelationshipAggregates.php","lineNumber":330,"sourceCode":"            class_basename($relation),\n        ));\n    }\n\n    private function getAggregateParentKey(Relation $relation): ?string\n    {\n        return match (true) {\n            $relation instanceof HasOneOrMany => $relation->getLocalKeyName(),\n            $relation instanceof BelongsTo => $relation->getForeignKeyName(),\n            $relation instanceof BelongsToMany => $relation->getParentKeyName(),\n            default => null,\n        };\n    }\n\n    /** The aggregated value does not exist in the documents, the server cannot use it. */\n    private function assertAggregateNotUsedInQuery(string $alias): void\n    {\n        if (isset($this->getQuery()->orders[$alias])) {\n            throw new LogicException(sprintf(\n                'Ordering by the aggregated field \"%s\" is not supported, as it is computed after the documents are read. Sort the results with the collection method \"sortBy\" instead.',\n                $alias,\n            ));\n        }\n    }\n}\n","sourceCodeStart":312,"sourceCodeEnd":337,"githubUrl":"https://github.com/mongodb/laravel-mongodb/blob/0634653039468ceb0268a69192bdac64469ed043/src/Helpers/QueriesRelationshipAggregates.php#L312-L337","documentation":"Aggregated fields (e.g. posts_count from withCount) do not exist in the stored MongoDB documents; they are computed after the documents are read. MongoDB cannot sort by them server-side, so orderBy() on an aggregate alias throws this LogicException at eager-load time.","triggerScenarios":"Calling Model::withCount('posts')->orderBy('posts_count')->get() (or orderByDesc) using the aggregate alias as the sort column.","commonSituations":"Developers porting SQL Eloquent code where orderBy('posts_count') works via a subquery select; in MongoDB the alias is computed client-side, so server-side sorting fails.","solutions":["Remove orderBy on the aggregate alias and sort in PHP with ->get()->sortBy('posts_count') (or sortByDesc).","Compute the aggregate first and sort the resulting collection: Model::withCount('posts')->get()->sortByDesc('posts_count')->values().","If server-side ordering is essential, denormalize the count into a real field maintained on write, then orderBy that field."],"exampleFix":"// before\nUser::withCount('posts')->orderByDesc('posts_count')->get();\n// after\nUser::withCount('posts')->get()->sortByDesc('posts_count')->values();","handlingStrategy":"try-catch","validationCode":"// Do not orderBy an aggregate alias; check before building the query\n$alias = 'posts_count';\nif (isset($query->orders[$alias])) {\n    throw new LogicException(\"Cannot order by computed aggregate {$alias}.\");\n}","typeGuard":"function ordersOnAggregate(object $query, string $alias): bool {\n    return isset($query->getQuery()->orders[$alias]);\n}","tryCatchPattern":"try {\n    $users = User::withCount('posts')->orderByDesc('posts_count')->get();\n} catch (\\LogicException $e) {\n    $users = User::withCount('posts')->get()->sortByDesc('posts_count')->values();\n}","preventionTips":["Never call orderBy with an aggregate alias on MongoDB models.","Sort aggregated results in PHP with collection sortBy/sortByDesc.","Denormalize frequently sorted counters into stored fields updated on write."],"tags":["mongodb","eloquent","aggregate","ordering","logic-exception"],"backgroundTag":"unsupported-operation","analyzedSha":"0634653039468ceb0268a69192bdac64469ed043","analyzedAt":"2026-09-15T02:56:37.067Z","contentChangedAt":"2026-09-15T02:56:37.067Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}