Skip to content

distinct_count_if

Description

Returns the number of distinct, non-null values that satisfy a given condition.

  • A document is counted only if the condition evaluates to true.
  • Duplicate values for the same expression are counted once per group.

Note

distinct_count_if is an aggregation function and must be used with a grouping keyword such as groupby.

Syntax

distinct_count_if(condition: bool, expression: any): number

Arguments

NameTypeRequiredDescription
conditionbooleantrueBoolean expression indicating whether the row should be counted
expressionanytrueExpression whose unique, non-null values are counted

Example

Use case: Count users who have experienced errors

Suppose you want to count how many unique users encountered an error for each application. Here, an error is defined as a log with $m.severity == ERROR.

Example data

{ "applicationname": "checkout-service", "username": "alice", "severity": "Error" },
{ "applicationname": "pager", "username": "bob", "severity": "Info" },
{ "applicationname": "checkout-service", "username": "alice", "severity": "Error" },
{ "applicationname": "checkout-service", "username": "charlie", "severity": "Error" }
{ "applicationname": "pager", "username": "bob", "severity": "Error" }
{ "applicationname": "checkout-service", "username": "charlie", "severity": "Error" }

Example query

groupby $l.applicationname aggregate distinct_count_if($m.severity == ERROR, $d.username) as users_with_errors

Example output

applicationnameusers_with_errors
checkout-service2
pager1