{"record":{"id":"791da0fbef90e0db","repo":"mongodb/laravel-mongodb","slug":"distinct-queries-cannot-be-used-for-pagination-use-groupby","errorCode":null,"errorMessage":"Distinct queries cannot be used for pagination. Use GroupBy instead","messagePattern":"Distinct queries cannot be used for pagination\\. Use GroupBy instead","errorType":"exception","errorClass":"BadMethodCallException","httpStatus":null,"severity":"error","filePath":"src/Query/Builder.php","lineNumber":1172,"sourceCode":"        return $this->performUpdate($query);\n    }\n\n    /**\n     * @return static\n     *\n     * @inheritdoc\n     */\n    #[Override]\n    public function newQuery()\n    {\n        return new static($this->connection, $this->grammar, $this->processor);\n    }\n\n    #[Override]\n    public function runPaginationCountQuery($columns = ['*'])\n    {\n        if ($this->distinct) {\n            throw new BadMethodCallException('Distinct queries cannot be used for pagination. Use GroupBy instead');\n        }\n\n        if ($this->groups || $this->havings) {\n            $without = $this->unions ? ['orders', 'limit', 'offset'] : ['columns', 'orders', 'limit', 'offset'];\n\n            $mql = $this->cloneWithout($without)\n                ->cloneWithoutBindings($this->unions ? ['order'] : ['select', 'order'])\n                ->toMql();\n\n            // Adds the $count stage to the pipeline\n            $mql['aggregate'][0][] = ['$count' => 'aggregate'];\n\n            return $this->collection->aggregate($mql['aggregate'][0], $mql['aggregate'][1])->toArray();\n        }\n\n        return parent::runPaginationCountQuery($columns);\n    }\n","sourceCodeStart":1154,"sourceCodeEnd":1190,"githubUrl":"https://github.com/mongodb/laravel-mongodb/blob/0634653039468ceb0268a69192bdac64469ed043/src/Query/Builder.php#L1154-L1190","documentation":"paginate()/paginate count queries cannot be built for queries that use distinct() in the MongoDB builder, because Mongo has no direct equivalent for counting distinct documents cheaply. The library throws before running so you don't get an incorrect count.","triggerScenarios":"Calling ->distinct('category')->paginate(15); Model::distinct(...)->paginate(...); ->distinct('x')->groupBy(...) combos still starting with distinct set; any pagination (or paginate count query) on a builder where $builder->distinct is truthy.","commonSituations":"Converting SQL code that relied on DISTINCT for pagination counts; faceted listing pages; devs wanting unique values per page.","solutions":["Replace ->distinct($col) with ->groupBy($col) before paginating; group-by count queries are supported.","Paginate the base query without distinct and deduplicate client-side after the page is fetched (if the count semantics allow).","Precompute the distinct values with ->aggregate(['$group' => ['_id' => '$col']]) and paginate the resulting collection.","If unique docs are guaranteed by the schema (e.g. unique index), simply drop the distinct() call."],"exampleFix":"// before\n$users = User::distinct('email')->paginate(20);\n// after\n$users = User::groupBy('email')->paginate(20);","handlingStrategy":"try-catch","validationCode":"if ($query->distinct) {\n    $query->groupBy($distinctColumn);\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Never combine distinct() with paginate().","Use groupBy() as the Mongo-native equivalent.","Precompute distinct values with aggregation for large sets."],"tags":["php","laravel-mongodb","pagination"],"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"}