Skip to content

fix: count() after groupBy() returns integer instead of Collection#3513

Draft
GromNaN wants to merge 1 commit into
mongodb:5.xfrom
GromNaN:fix/count-with-groupby
Draft

fix: count() after groupBy() returns integer instead of Collection#3513
GromNaN wants to merge 1 commit into
mongodb:5.xfrom
GromNaN:fix/count-with-groupby

Conversation

@GromNaN
Copy link
Copy Markdown
Member

@GromNaN GromNaN commented May 21, 2026

Summary

  • Fixes GroupBy with count does not work #3512
  • Overrides count() in Query\Builder to handle groupBy() correctly
  • When groups are present, runs a $match + $group + $count aggregation pipeline to return the number of distinct groups as an integer
  • Mirrors the pattern already used in runPaginationCountQuery()

Problem

->groupBy('status')->count() triggered a PHP warning and returned 1:

WARNING Object of class Illuminate\Support\Collection could not be converted to int

The root cause: aggregate() returns a Collection when $this->groups is set, but count() casts the return value to (int).

Note on SQL behavior

For reference, Eloquent SQL generates SELECT count(*) as aggregate FROM ... GROUP BY status, which returns one row per group. Laravel takes $results[0]['aggregate'], i.e. the count of the first (arbitrary) group — not the number of groups, and not the total count.

Our implementation returns the number of distinct groups, which is consistent with runPaginationCountQuery() behavior and more predictable than the SQL equivalent.

Test plan

  • testCountWithGroupBy covers the fix (multiple groups, filtered result, no match)
  • testAggregateGroupBy confirms aggregateByGroup('count') still returns per-group Collection unchanged

When count() was called on a query with groupBy(), the aggregate()
method returned a Collection of per-group results instead of a scalar.
Laravel's count() casts the return value to int, causing a PHP warning
and always returning 1.

Override count() to use a $match + $group + $count aggregation pipeline
when groups are present, returning the number of distinct groups.
This mirrors the pattern used in runPaginationCountQuery().

Fixes mongodb#3512
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GroupBy with count does not work

1 participant