{"record":{"id":"c316ea490f5314ff","repo":"mongodb/laravel-mongodb","slug":"aggregate-function-s-is-not-supported-by-mongodb-supported","errorCode":null,"errorMessage":"Aggregate function \"%s\" is not supported by MongoDB. Supported functions are: %s.","messagePattern":"Aggregate function \"(.+?)\" is not supported by MongoDB\\. Supported functions are: (.+?)\\.","errorType":"exception","errorClass":"InvalidArgumentException","httpStatus":null,"severity":"error","filePath":"src/Helpers/QueriesRelationshipAggregates.php","lineNumber":62,"sourceCode":" *\n * @internal\n */\ntrait QueriesRelationshipAggregates\n{\n    private const AGGREGATE_FUNCTIONS = ['count', 'exists', 'sum', 'avg', 'min', 'max'];\n\n    /** @var array<string, array{name: string, function: string, column: string, parentKey: ?string, constraints: Closure}> */\n    private array $withAggregates = [];\n\n    /** @inheritdoc */\n    public function withAggregate($relations, $column, $function = null)\n    {\n        if (empty($relations)) {\n            return $this;\n        }\n\n        if (! in_array($function, self::AGGREGATE_FUNCTIONS, true)) {\n            throw new InvalidArgumentException(sprintf(\n                'Aggregate function \"%s\" is not supported by MongoDB. Supported functions are: %s.',\n                $function ?? 'null',\n                implode(', ', self::AGGREGATE_FUNCTIONS),\n            ));\n        }\n\n        if (! is_string($column)) {\n            throw new InvalidArgumentException('The aggregate column name must be a string.');\n        }\n\n        if (str_starts_with($column, '$')) {\n            throw new InvalidArgumentException(sprintf(\n                'The aggregate column name \"%s\" must not start with \"$\".',\n                $column,\n            ));\n        }\n\n        foreach ($this->parseWithRelations(is_array($relations) ? $relations : [$relations]) as $name => $constraints) {","sourceCodeStart":44,"sourceCodeEnd":80,"githubUrl":"https://github.com/mongodb/laravel-mongodb/blob/0634653039468ceb0268a69192bdac64469ed043/src/Helpers/QueriesRelationshipAggregates.php#L44-L80","documentation":"The QueriesRelationshipAggregates helper restricts withAggregate()/withCount-style aggregation to a known whitelist (self::AGGREGATE_FUNCTIONS, e.g. count, sum, avg, min, max). Passing any other function name throws InvalidArgumentException listing the supported ones.","triggerScenarios":"Calling withAggregate('relation', 'median', 'column') or withCount-like APIs with an unsupported function string, or passing null as the function.","commonSituations":"Porting SQL-flavored Laravel code using functions MongoDB does not support (e.g. 'stddev', 'json_agg'); typos like 'avrg'; dynamic function names from user input.","solutions":["Use one of the supported functions listed in the error message (e.g. sum, avg, min, max, count)","Compute unsupported aggregates client-side or via a raw aggregation pipeline instead","Fix typos in the function name","Validate user-supplied function names against the whitelist before calling"],"exampleFix":"// before\n$query->withAggregate('orders', 'median', 'total');\n// after\n$query->withAggregate('orders', 'avg', 'total');","handlingStrategy":"validation","validationCode":"const SUPPORTED = ['count','sum','avg','min','max'];\nif (!in_array($function, SUPPORTED, true)) {\n    throw new InvalidArgumentException(\"Unsupported aggregate: $function\");\n}","typeGuard":"function isSupportedAggregate(?string $function): bool {\n    return $function !== null && in_array($function, \\MongoDB\\Laravel\\Helpers\\QueriesRelationshipAggregates::AGGREGATE_FUNCTIONS, true);\n}","tryCatchPattern":"try {\n    $query->withAggregate('orders', $fn, 'total');\n} catch (InvalidArgumentException $e) {\n    if (str_contains($e->getMessage(), 'not supported by MongoDB')) {\n        Log::warning('Unsupported aggregate requested, defaulting to sum');\n        $query->withAggregate('orders', 'sum', 'total');\n    } else {\n        throw $e;\n    }\n}","preventionTips":["Consult AGGREGATE_FUNCTIONS in QueriesRelationshipAggregates before dynamic use","Map SQL-only aggregate names (stddev, median) to supported ones upstream","Whitelist user-supplied aggregate functions against the constant"],"tags":["eloquent","aggregates","api-misuse"],"backgroundTag":"invalid-enum-value","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"}