mongodb/laravel-mongodb · error · BadMethodCallException

Aggregation builder requires package mongodb/builder 0.2+

Error message

Aggregation builder requires package mongodb/builder 0.2+

What it means

Builder::aggregate() can return a fluent AggregationBuilder (from mongodb/builder) when no function is given. That builder requires the FluentFactoryTrait from mongodb/builder 0.2+; if the trait class does not exist, this BadMethodCallException is thrown, noting the package will later merge into mongodb/mongodb.

Solutions

  1. Run: composer require mongodb/builder:^0.2
  2. Alternatively call ->aggregate('count'/'avg'/...) with an explicit function instead of the fluent builder.
  3. Upgrade mongodb/mongodb and mongodb/builder together to compatible versions.

Example fix

// before
composer require mongodb/mongodb  # builder missing
// after
composer require mongodb/mongodb mongodb/builder:^0.2
Defensive patterns

Strategy: validation

Validate before calling

if (! trait_exists(MongoDB\Builder\FluentFactoryTrait::class)) {
    throw new RuntimeException('composer require mongodb/builder:^0.2 for aggregation builder');
}
$agg = Model::aggregate(null);

Type guard

function aggregationBuilderAvailable(): bool { return trait_exists(MongoDB\Builder\FluentFactoryTrait::class); }

Try / catch

try {
    $agg = Model::aggregate(null);
} catch (BadMethodCallException $e) {
    if (str_contains($e->getMessage(), 'mongodb/builder')) {
        // fall back to function-based aggregation
        $agg = Model::aggregate('count');
    } else { throw $e; }
}

Prevention

When it happens

Trigger: Calling ->aggregate() with no aggregation function (null $function) to obtain an AggregationBuilder while mongodb/builder is absent or older than 0.2.

Common situations: Projects using only mongodb/mongodb without the separate mongodb/builder package, or a composer.lock pinned to a pre-0.2 builder.

Understand the failure class

Background: "X is not installed. Please install it with pip install Y": missing optional dependency errors — ImportError/ValueError raised when a library's optional extra was never installed — this error's family across 22 libraries.

Related errors


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

Appendix: source

Thrown at src/Query/Builder.php:578

            'orders' => $this->orders,
            'offset' => $this->offset,
            'limit' => $this->limit,
            'aggregate' => $this->aggregate,
        ];

        return md5(serialize(array_values($key)));
    }

    /** @return ($function is null ? AggregationBuilder : mixed) */
    #[Override]
    public function aggregate($function = null, $columns = ['*'])
    {
        assert(is_array($columns), new TypeError(sprintf('Argument #2 ($columns) must be of type array, %s given', get_debug_type($columns))));

        if ($function === null) {
            if (! trait_exists(FluentFactoryTrait::class)) {
                // This error will be unreachable when the mongodb/builder package will be merged into mongodb/mongodb
                throw new BadMethodCallException('Aggregation builder requires package mongodb/builder 0.2+');
            }

            if ($columns !== ['*']) {
                throw new InvalidArgumentException('Columns cannot be specified to create an aggregation builder. Add a $project stage instead.');
            }

            if ($this->wheres) {
                throw new BadMethodCallException('Aggregation builder does not support previous query-builder instructions. Use a $match stage instead.');
            }

            return new AggregationBuilder($this->collection, $this->options);
        }

        $this->aggregate = [
            'function' => $function,
            'columns' => $columns,
        ];

View on GitHub (pinned to 0634653039)