mongodb/laravel-mongodb · error · InvalidArgumentException

Aggregate function " " is not supported by MongoDB…

Error message

Aggregate function "%s" is not supported by MongoDB. Supported functions are: %s.

What it means

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.

Solutions

  1. Use one of the supported functions listed in the error message (e.g. sum, avg, min, max, count)
  2. Compute unsupported aggregates client-side or via a raw aggregation pipeline instead
  3. Fix typos in the function name
  4. Validate user-supplied function names against the whitelist before calling

Example fix

// before
$query->withAggregate('orders', 'median', 'total');
// after
$query->withAggregate('orders', 'avg', 'total');
Defensive patterns

Strategy: validation

Validate before calling

const SUPPORTED = ['count','sum','avg','min','max'];
if (!in_array($function, SUPPORTED, true)) {
    throw new InvalidArgumentException("Unsupported aggregate: $function");
}

Type guard

function isSupportedAggregate(?string $function): bool {
    return $function !== null && in_array($function, \MongoDB\Laravel\Helpers\QueriesRelationshipAggregates::AGGREGATE_FUNCTIONS, true);
}

Try / catch

try {
    $query->withAggregate('orders', $fn, 'total');
} catch (InvalidArgumentException $e) {
    if (str_contains($e->getMessage(), 'not supported by MongoDB')) {
        Log::warning('Unsupported aggregate requested, defaulting to sum');
        $query->withAggregate('orders', 'sum', 'total');
    } else {
        throw $e;
    }
}

Prevention

When it happens

Trigger: Calling withAggregate('relation', 'median', 'column') or withCount-like APIs with an unsupported function string, or passing null as the function.

Common situations: 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.

Understand the failure class

Background: Invalid enum value errors: "Unknown type", "Invalid scope", "must be one of" — when a string is not on the library's allowed list — this error's family across 23 libraries.

Related errors


AI-assisted analysis of mongodb/laravel-mongodb@0634653039 (2026-09-15). Data as JSON: /api/errors/c316ea490f5314ff. Report an issue: GitHub.

Appendix: source

Thrown at src/Helpers/QueriesRelationshipAggregates.php:62

 *
 * @internal
 */
trait QueriesRelationshipAggregates
{
    private const AGGREGATE_FUNCTIONS = ['count', 'exists', 'sum', 'avg', 'min', 'max'];

    /** @var array<string, array{name: string, function: string, column: string, parentKey: ?string, constraints: Closure}> */
    private array $withAggregates = [];

    /** @inheritdoc */
    public function withAggregate($relations, $column, $function = null)
    {
        if (empty($relations)) {
            return $this;
        }

        if (! in_array($function, self::AGGREGATE_FUNCTIONS, true)) {
            throw new InvalidArgumentException(sprintf(
                'Aggregate function "%s" is not supported by MongoDB. Supported functions are: %s.',
                $function ?? 'null',
                implode(', ', self::AGGREGATE_FUNCTIONS),
            ));
        }

        if (! is_string($column)) {
            throw new InvalidArgumentException('The aggregate column name must be a string.');
        }

        if (str_starts_with($column, '$')) {
            throw new InvalidArgumentException(sprintf(
                'The aggregate column name "%s" must not start with "$".',
                $column,
            ));
        }

        foreach ($this->parseWithRelations(is_array($relations) ? $relations : [$relations]) as $name => $constraints) {

View on GitHub (pinned to 0634653039)