Session: Querying: How to Filter by Field Presence


  • To filter documents by whether they contain a particular field, use the LINQ extension method WhereExists() accessible from the Document Query.

  • If a document doesn't contain the specified field, it is excluded from the query results.

  • In this page:


Syntax

IDocumentQuery<T> WhereExists(string fieldName);

IDocumentQuery<T> WhereExists<TValue>(Expression<Func<T, TValue>> propertySelector);
Parameters Type Description
fieldName string The name of the field you want to filter by
propertySelector Expression<Func<T,TValue>> The path to the field you want to filter by

Examples

Filter by Field Name

List<Employee> results = session
    .Advanced
    .DocumentQuery<Employee>()
    .WhereExists("FirstName")
    .ToList();
List<Employee> results = await asyncSession
    .Advanced
    .AsyncDocumentQuery<Employee>()
    .WhereExists("FirstName")
    .ToListAsync();
from Employees 
where exists("FirstName")


Filter by the Path to a Field

This is done by passing the path as a lambda expression:

List<Employee> results = session
    .Advanced
    .DocumentQuery<Employee>()
    .WhereExists(x => x.Address.Location.Latitude)
    .ToList();
List<Employee> results = await asyncSession
    .Advanced
    .AsyncDocumentQuery<Employee>()
    .WhereExists(x => x.Address.Location.Latitude)
    .ToListAsync();
from Employees 
where exists(Address.Location.Latitude)

The path can also be passed as a string:

List<Employee> results = session
    .Advanced
    .DocumentQuery<Employee>()
    .WhereExists("Address.Location.Latitude")
    .ToList();
List<Employee> results = await asyncSession
    .Advanced
    .AsyncDocumentQuery<Employee>()
    .WhereExists("Address.Location.Latitude")
    .ToListAsync();
from Employees 
where exists("Address.Location.Latitude")