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
Arguments
| Name | Type | Required | Description |
|---|---|---|---|
| condition | boolean | true | Boolean expression indicating whether the row should be counted |
| expression | any | true | Expression 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
| applicationname | users_with_errors |
|---|---|
| checkout-service | 2 |
| pager | 1 |
Theme
Light