$sum computes the total of a field across matching documents.
If missing is set, missing fields contribute that fallback value.
By default, $sum returns 0 when no values are collected — either no documents match, or the matching documents all have a missing/null value for the field and no missing fallback is set. Set nullIfNoMatch to true to return null instead, so you can distinguish that case from a real total of zero.
Compatibility#
| Field Type | Supported |
|---|---|
| TEXT | No |
| U64/I64/F64 | Yes |
| DATE | Yes |
| BOOL | Yes |
| KEYWORD | No |
| FACET | No |
Field must be FAST.
Arguments#
| Argument | Type | Required | Description |
|---|---|---|---|
field | string | Yes | Field to aggregate. |
missing | number | No | Fallback value for missing fields. |
nullIfNoMatch | boolean | No | Return null instead of 0 when no values are collected. Default: false. |
Output#
With nullIfNoMatch: true, an aggregation with no collected values (for example, the filter above matches no documents) returns:
Without nullIfNoMatch, the same aggregation returns 0. This option does not change results where at least one value was collected, including a real sum of zero.