Repository navigation
Feature Request: Support Count with Where Clauses #5224
Replies: 1 comment
|
Good news: this already works in current Marten, so no contribution is needed. I tested it against PostgreSQL 17 with an var rows = await session.Query<Order>()
.Select(x => new { x.Name, Active = x.Lines.Count(l => l.IsActive) })
.ToListAsync();
// a=2 | b=0It runs server-side. select (jsonb_build_object('Name', d.data ->> 'Name')
|| jsonb_strip_nulls(jsonb_build_object('Active',
jsonb_array_length(jsonb_path_query_array(d.data, '$.Lines[*] ? (@.IsActive == $val1)', :p0)))))
as data from mt.mt_doc_order as d;So the predicate becomes a JSONPath filter and only the count comes back. The collection isn't loaded into memory. The version matters. I ran the same program against several releases:
So upgrading to 9.18.0 or later fixes it. On 9.56.0 these also work:
If you're stuck below 9.18 for now, the only workaround I'd trust is selecting the collection and counting in memory, since on 9.17.1 the |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Add support for using
Count()with a predicate when projecting documents withSelect(), similar to the collection aggregate support introduced in Marten 9.14.1.Example
Given a document with a collection:
It would be useful to support queries such as:
Ideally, this should be translated to PostgreSQL and calculated server-side rather than requiring the document or collection to be materialized in memory.
Expected Behavior
Support
Count(predicate)as part of a projection, for example:This should behave consistently with the existing support for collection aggregates such as
Sum,Min,Max, andAverage.Motivation
Counting collection elements matching a condition is a common projection requirement. Supporting this directly in
Select()would allow applications to retrieve calculated collection counts efficiently without loading the entire collection.Related
Marten 9.14.1 added support for collection aggregates in
Where()clauses, includingSum,Min,Max, andAverage.It would be great to extend this functionality to support conditional
Count()expressions in projections as well.P.S. I’d be happy to contribute this myself, but I’m having a hard time figuring out where to get started in the codebase.
All reactions