Querying Documents with Linq
Marten has its own LINQ provider. It translates a subset of the standard LINQ operators, plus some Marten-specific ones, to PostgreSQL. You start a query with IQuerySession.Query<T>() or IDocumentSession.Query<T>(). Both return an IMartenQueryable<T>, which implements the standard IQueryable<T> for the document type T.
/// <summary>
/// Use Linq operators to query the documents
/// stored in Postgresql
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
new IMartenQueryable<T> Query<T>() where T : notnull;WARNING
Every Marten query runs asynchronously. The synchronous ToList(), First(), Count(), foreach and the rest still compile, because they come from System.Linq, but they throw NotSupportedException naming the asynchronous operator to use instead. Use ToListAsync(), FirstAsync(), CountAsync() and the other *Async() operators, or ToAsyncEnumerable() to stream the results. See the migration guide.
What Marten Supports
The tables below list the LINQ operators and expression shapes Marten translates to SQL. Each row links to an example. Marten does not run part of a query in memory to make up for a shape it cannot translate. It throws, and the last table says which exception you get and what to do instead. The one exception is the last step of an object projection: a Select() into an object that SQL can't build is completed on the client, after the query runs.
Filtering with Where()
| Shape | Example |
|---|---|
==, !=, >, >=, <, <=, &&, || and ! on members, including members of members (x.Inner.Number) and comparisons between two members | Filtering Documents |
Arithmetic and % inside a predicate | Modulo Queries |
Boolean members: x.Flag, !x.Flag, x.Flag == false | Searching with Boolean Flags |
== null, != null and HasValue | Searching for NULL Values |
Captured variables, including the optional filter !captured.HasValue || x.Id == captured | Optional Filters |
A local array, List<T> or HashSet<T>: ids.Contains(x.Id), a SQL IN | Contains() over a Local Collection |
IsOneOf() and In() | IsOneOf |
CompareTo() compared with 0, on numbers, dates and Guid | CompareTo() |
Raw SQL with MatchesSql() and MatchesJsonPath() | Mixing Raw SQL with Linq |
Full-text search: Search(), PlainTextSearch(), PhraseSearch(), WebStyleSearch(), NgramSearch() | Text Search |
Soft-deleted documents: MaybeDeleted() and the other soft-delete filters | Querying a Soft Deleted Document Type |
Tenancy: AnyTenant() and TenantIsOneOf() | Querying Multi-Tenanted Documents |
C# 15 union members on .NET 11: x.Payment.Value is Card, ((Card)x.Payment.Value).Last4 | Querying C# Union Members |
Strings
| Shape | Example |
|---|---|
StartsWith(), EndsWith(), Contains() and Equals() | Substring Searches |
The same with StringComparison.OrdinalIgnoreCase, and EqualsIgnoreCase() | Case-Insensitive Searches |
string.IsNullOrEmpty() and string.IsNullOrWhiteSpace() | Null, Empty and Whitespace |
ToLower(), ToUpper(), their Invariant forms, Trim() and Length | Case, Trim and Length |
string.Compare() and CompareTo() compared with 0 | Comparing Strings |
Regex.IsMatch(), with RegexOptions.IgnoreCase | Regular Expressions |
Collections and Child Collections
| Shape | Example |
|---|---|
Any(), Any(predicate), Contains(value), !Contains(value) and All(predicate) | Quantifier Operations |
Any() inside Any() | Nested Any() |
Count(), Count(predicate) and Length compared with a number | Querying within Value IEnumerables |
Sum(), Min(), Max() and Average() of a child collection inside a predicate | How Marten Translates Collection Predicates |
An element by position: x.Values[1], x.Grid[1][0], ElementAt(1) | Reading an Element by Position |
Dictionaries: ContainsKey(), Keys, Values, Count and the indexer x.Tags["color"] | Querying Dictionaries |
IsSupersetOf() and IsSubsetOf() | IsSupersetOf |
IsEmpty(), true for an empty or null collection | IsEmpty |
Projections with Select()
| Shape | Example |
|---|---|
| A member, or a member of a member | Select() |
An anonymous type, a DTO or a record built from members, run as jsonb_build_object() | Server-Side JSON Projections |
Count() and Count(predicate) of a child collection inside an object projection | Counting a Child Collection |
A computed value: arithmetic, %, widening casts, string concatenation, ToUpper(), ToLower(), Length, ToString() of an integer or a Guid | Computed Values in Select() |
Where(), OrderBy(), Distinct(), paging and aggregates after a Select() | Operators after Select() |
| An object projection that contains anything else, run on the client | Projections That Can't Be Expressed in SQL |
Raw SQL in a projection with ExplicitSql<T>() | Raw SQL in Select() |
SelectMany()
| Shape | Example |
|---|---|
| Flatten a collection of values or of child documents | SelectMany() |
Where(), Select(), OrderBy(), Distinct(), paging, First(), Single(), Count() and aggregates after it | Operators after SelectMany() |
Take() and Skip() before it page the documents; after it they page the flattened rows | Paging and SelectMany() |
Ordering and Paging
| Shape | Example |
|---|---|
OrderBy(), OrderByDescending(), ThenBy() and ThenByDescending() | Ordering Results |
A computed key, OrderBy(x => -x.Number), or an element by position | Computed Ordering Keys |
Case-insensitive ordering with StringComparer.OrdinalIgnoreCase | Case-insensitive Ordering |
Ordering by member name: OrderBy("Date") | Ordering with Dynamic Properties |
Raw SQL with OrderBySql() and ThenBySql() | Ordering with Raw SQL |
Take() and Skip(); CountAsync() after them counts the page | Partitioning Operators |
ToPagedListAsync() and Stats() | Paging |
Keyset paging with ToJsonPageByCursorAsync() | Keyset (Cursor) Pagination |
Results, Aggregates and Element Operators
| Shape | Example |
|---|---|
ToListAsync() | Querying for All Documents |
ToAsyncEnumerable() | Querying to IAsyncEnumerable |
FirstAsync(), FirstOrDefaultAsync(), SingleAsync() and SingleOrDefaultAsync() | Element Operations |
AnyAsync(), CountAsync(), LongCountAsync(), MinAsync(), MaxAsync(), SumAsync() and AverageAsync() | Aggregate Functions |
Distinct() | Distinct() |
DistinctBy() after a Select(), as DISTINCT ON | DistinctBy() |
Grouping and Joins
| Shape | Example |
|---|---|
GroupBy() on one or more keys, with Count(), Sum(), Min(), Max() and Average() | GroupBy() |
Where() after GroupBy(), as HAVING | HAVING |
| Ordering, paging and counting groups | Ordering and Paging Groups |
GroupJoin() followed by SelectMany(), as an inner or left join | Inner Join |
Join(), LeftJoin() and RightJoin() | Join, LeftJoin, RightJoin and FullJoin |
Count(), Distinct(), Sum() and Max() over a join | With Aggregation |
GroupBy() and computed OrderBy() keys over a join | Grouping and Ordering over a Join |
Related Documents
| Shape | Example |
|---|---|
Include() one related document | Include a Single Document |
Include() into a list or a dictionary, including from an array of ids | Include Many Documents |
Include() with a filter on the included documents | Filtering Included Documents |
Include() on any member, including the children of the queried document | Mapping to Documents on Any Property |
Not Supported
| Shape | What happens | Do this instead |
|---|---|---|
Synchronous execution: ToList(), ToArray(), foreach, First(), Single(), Count(), Any(), Sum(), and anything else that enumerates the query, such as .NET 9's CountBy() | NotSupportedException naming the asynchronous operator | ToListAsync(), FirstAsync() and the other *Async() operators, or ToAsyncEnumerable() |
ToAsyncEnumerable() in a file without using Marten; | Binds to .NET 10's AsyncEnumerable.ToAsyncEnumerable(), which enumerates the query synchronously: NotSupportedException | Add using Marten;. See Querying to IAsyncEnumerable |
ToPagedList() | NotSupportedException | ToPagedListAsync() |
Last() and LastOrDefault() | NotSupportedException. There is no asynchronous version. Inside a compiled query's QueryIs(), InvalidOperationException | Reverse the ordering and use FirstAsync() or FirstOrDefaultAsync(), or First() inside a compiled query |
ElementAt() and ElementAtOrDefault() on the query itself | NotSupportedException | Skip(index), then FirstAsync() or FirstOrDefaultAsync() |
Aggregate() | NotSupportedException | SumAsync() and the other aggregates, or load the rows with ToListAsync() and aggregate in memory |
Reverse(), Concat(), Union(), Zip(), TakeWhile(), SkipWhile() and any other operator not listed on this page | BadLinqExpressionException | MatchesSql(), session.QueryAsync<T>(sql), or load the rows and apply the operator in memory |
A method call in Where() that Marten has no translation for, such as x.Name.IsNormalized() | NotSupportedException | MatchesSql(), or add your own translation |
A computed Select() or OrderBy() value that PostgreSQL would not compute the way .NET does: a Math call, ? :, Substring(), decimal division, a narrowing cast, floating point % | BadLinqExpressionException. Marten does not fall back to the client for a scalar Select() | Select the members and compute in memory, or project into an object, which runs on the client |
OrderBy() after a Select() into an anonymous type, a DTO or another document | BadLinqExpressionException | Order before the Select() |
After SelectMany(), a Select() into an object followed by Where(), OrderBy(), Distinct() or an aggregate, or a GroupBy() of the flattened rows | BadLinqExpressionException | Apply the operator before the Select() |
DistinctBy() directly on the documents | BadLinqExpressionException | Select() first, then DistinctBy() |
A negative index, x.Values[-1] | BadLinqExpressionException | Index from the start of the array |
CompareTo() compared with anything other than 0 | BadLinqExpressionException | Compare the result with 0 |
GroupJoin() as the last operator | NotSupportedException | Follow it with SelectMany() |
FullJoin(), and the join shapes listed under Join, LeftJoin, RightJoin and FullJoin | BadLinqExpressionException | Query each side and combine in memory, or use session.QueryAsync<T>(sql) |
ToJsonArray(), StreamJsonArray() and the other raw JSON methods over a projection that runs on the client | BadLinqExpressionException | ToListAsync() |
| Union shapes Marten cannot tell apart in the stored JSON | BadLinqExpressionException | See What Marten Refuses |
Querying for All Documents
To query for all documents of a type - not that you would do this very often outside of testing - use the Query<T>() method like this:
public async Task get_all_documents_of_a_type(IDocumentSession session)
{
// ToListAsync() executes the query
var targets = await session.Query<Target>().ToListAsync();
}Supported .NET Types
Marten's Linq support has been tested against these .NET types:
StringInt32andInt64(intandlong)Decimal,DoubleandSingle(float)BooleanGuidDateTime,DateTimeOffset,DateOnly,TimeOnlyandTimeSpanEnumvalues, stored as integers or as stringsNullable<T>of all of the above types- Strong-typed identifiers and other value types. See LINQ Support for strong-typed identifiers
- C# 15 unions on .NET 11. See Querying C# Union Members
For full-text search, see Full Text Searching.

