Querying: Distinct

The distinct() method allows you to remove duplicates from query results.
Items are compared based on the fields listed in the select section of the query.

Sample Query with Distinct

// returns sorted list of countries w/o duplicates
const countries = await session
from Orders 
select distinct ShipTo.Country

Paging with Distinct

A special approach must be used when calling distinct() while paging.
Please read the dedicated article about paging through tampered results.

Count with Distinct

Use count() in combination with distinct() to get the number of unique items. Similar to toList(), count() triggers query execution on the server-side.

// results will contain the number of unique countries
const numberOfCountries = await session

Performance Cost and an Alternative Approach

Please keep in mind that using count() with distinct() might not be efficient for large sets of data due to the need to scan all of the index results in order to find all the unique values.

  • Getting the distinct items' count can also be achieved by creating a Map-Reduce index that will aggregate data by the field for which distinct count results are needed.
  • This is more efficient since computations are done during indexing time and not at query time.
    The entire dataset is Indexed once, whereafter the aggregated value is always kept up to date as indexing will occur only for new/modified data.

Map-Reduce Index Sample:

Index definition:

class Employees_ByCountry extends AbstractJavaScriptIndexCreationTask {

    constructor() {

        // The map phase indexes the country listed in each employee document
        // countryCount is assigned with 1, which will be aggregated in the reduce phase
        this.map("Employees", employee => {
            return {
                country: employee.Address.Country,
                countryCount: 1

        // The reduce phase will group the country results and aggregate the countryCount
        this.reduce(results => results.groupBy(x => x.country).aggregate(g => {
            return {
                country: g.key,
                countryCount: g.values.reduce((p, c) => p + c.countryCount, 0)

Query the index:

// Query the map - reduce index defined above
const session = documentStore.openSession();
const queryResult = await session.query({ indexName: 'Employees/ByCountry' })
    .whereEquals('country', country)

const numberOfEmployeesFromCountry = queryResult != null ? queryResult.countryCount : 0;

Combining Faceted Queries with Map-Reduce

Faceted queries can be used together with a map-reduce index as another alternative approach.
See a C# example for Implementing a count(distinct) query in RavenDB.