Skip to content

Use this LLM Friendly Docs as an MCP server for Marten.

The search box in the website knows all the secrets—try it!

For any queries, join our Discord Channel to reach us faster.

JasperFx Logo

JasperFx provides formal support for Marten and other JasperFx libraries. Please check our Support Plans for more details.

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.

cs
/// <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;

snippet source | anchor

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() ​

ShapeExample
==, !=, >, >=, <, <=, &&, || and ! on members, including members of members (x.Inner.Number) and comparisons between two membersFiltering Documents
Arithmetic and % inside a predicateModulo Queries
Boolean members: x.Flag, !x.Flag, x.Flag == falseSearching with Boolean Flags
== null, != null and HasValueSearching for NULL Values
Captured variables, including the optional filter !captured.HasValue || x.Id == capturedOptional Filters
A local array, List<T> or HashSet<T>: ids.Contains(x.Id), a SQL INContains() over a Local Collection
IsOneOf() and In()IsOneOf
CompareTo() compared with 0, on numbers, dates and GuidCompareTo()
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 filtersQuerying 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).Last4Querying C# Union Members

Strings ​

ShapeExample
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 LengthCase, Trim and Length
string.Compare() and CompareTo() compared with 0Comparing Strings
Regex.IsMatch(), with RegexOptions.IgnoreCaseRegular Expressions

Collections and Child Collections ​

ShapeExample
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 numberQuerying within Value IEnumerables
Sum(), Min(), Max() and Average() of a child collection inside a predicateHow 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 collectionIsEmpty

Projections with Select() ​

ShapeExample
A member, or a member of a memberSelect()
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 projectionCounting a Child Collection
A computed value: arithmetic, %, widening casts, string concatenation, ToUpper(), ToLower(), Length, ToString() of an integer or a GuidComputed 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 clientProjections That Can't Be Expressed in SQL
Raw SQL in a projection with ExplicitSql<T>()Raw SQL in Select()

SelectMany() ​

ShapeExample
Flatten a collection of values or of child documentsSelectMany()
Where(), Select(), OrderBy(), Distinct(), paging, First(), Single(), Count() and aggregates after itOperators after SelectMany()
Take() and Skip() before it page the documents; after it they page the flattened rowsPaging and SelectMany()

Ordering and Paging ​

ShapeExample
OrderBy(), OrderByDescending(), ThenBy() and ThenByDescending()Ordering Results
A computed key, OrderBy(x => -x.Number), or an element by positionComputed Ordering Keys
Case-insensitive ordering with StringComparer.OrdinalIgnoreCaseCase-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 pagePartitioning Operators
ToPagedListAsync() and Stats()Paging
Keyset paging with ToJsonPageByCursorAsync()Keyset (Cursor) Pagination

Results, Aggregates and Element Operators ​

ShapeExample
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 ONDistinctBy()

Grouping and Joins ​

ShapeExample
GroupBy() on one or more keys, with Count(), Sum(), Min(), Max() and Average()GroupBy()
Where() after GroupBy(), as HAVINGHAVING
Ordering, paging and counting groupsOrdering and Paging Groups
GroupJoin() followed by SelectMany(), as an inner or left joinInner Join
Join(), LeftJoin() and RightJoin()Join, LeftJoin, RightJoin and FullJoin
Count(), Distinct(), Sum() and Max() over a joinWith Aggregation
GroupBy() and computed OrderBy() keys over a joinGrouping and Ordering over a Join

Related Documents ​

ShapeExample
Include() one related documentInclude a Single Document
Include() into a list or a dictionary, including from an array of idsInclude Many Documents
Include() with a filter on the included documentsFiltering Included Documents
Include() on any member, including the children of the queried documentMapping to Documents on Any Property

Not Supported ​

ShapeWhat happensDo 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 operatorToListAsync(), 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: NotSupportedExceptionAdd using Marten;. See Querying to IAsyncEnumerable
ToPagedList()NotSupportedExceptionToPagedListAsync()
Last() and LastOrDefault()NotSupportedException. There is no asynchronous version. Inside a compiled query's QueryIs(), InvalidOperationExceptionReverse the ordering and use FirstAsync() or FirstOrDefaultAsync(), or First() inside a compiled query
ElementAt() and ElementAtOrDefault() on the query itselfNotSupportedExceptionSkip(index), then FirstAsync() or FirstOrDefaultAsync()
Aggregate()NotSupportedExceptionSumAsync() 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 pageBadLinqExpressionExceptionMatchesSql(), 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()NotSupportedExceptionMatchesSql(), 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 documentBadLinqExpressionExceptionOrder before the Select()
After SelectMany(), a Select() into an object followed by Where(), OrderBy(), Distinct() or an aggregate, or a GroupBy() of the flattened rowsBadLinqExpressionExceptionApply the operator before the Select()
DistinctBy() directly on the documentsBadLinqExpressionExceptionSelect() first, then DistinctBy()
A negative index, x.Values[-1]BadLinqExpressionExceptionIndex from the start of the array
CompareTo() compared with anything other than 0BadLinqExpressionExceptionCompare the result with 0
GroupJoin() as the last operatorNotSupportedExceptionFollow it with SelectMany()
FullJoin(), and the join shapes listed under Join, LeftJoin, RightJoin and FullJoinBadLinqExpressionExceptionQuery 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 clientBadLinqExpressionExceptionToListAsync()
Union shapes Marten cannot tell apart in the stored JSONBadLinqExpressionExceptionSee 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:

cs
public async Task get_all_documents_of_a_type(IDocumentSession session)
{
    // ToListAsync() executes the query
    var targets = await session.Query<Target>().ToListAsync();
}

snippet source | anchor

Supported .NET Types ​

Marten's Linq support has been tested against these .NET types:

  1. String
  2. Int32 and Int64 (int and long)
  3. Decimal, Double and Single (float)
  4. Boolean
  5. Guid
  6. DateTime, DateTimeOffset, DateOnly, TimeOnly and TimeSpan
  7. Enum values, stored as integers or as strings
  8. Nullable<T> of all of the above types
  9. Strong-typed identifiers and other value types. See LINQ Support for strong-typed identifiers
  10. C# 15 unions on .NET 11. See Querying C# Union Members

For full-text search, see Full Text Searching.

Released under the MIT License.