Skip to content

firstNonNull - Find the first non-null value in the list of arguments

firstNonNull will take a list of arguments and return the first value it finds, in the order of the arguments, that is not null

NOTE: This will only work on scalar values, like number, string or timestamp. It will not work on objects.

Syntax

firstNonNull(value: any, ...values: any): any

Arguments

NameTypeRequiredDescription
valueanytrueThe first argument. Will be checked for a non-null value first
...valuesanytrueAll subsequent arguments, in order they should be checked

Example - Selecting from unconsistent fields for the same value

Consider the following log documents:

{
    "userId": "123",
    "user_id": null,
    "user_identifier: null
},
{
    "userId": null,
    "user_id": "456",
    "user_identifier: null
},
{
    "userId": null,
    "user_id": null,
    "user_identifier: "789"
}

As we can see, there are multiple different fields in which a user ID can appear. This is a very common situation with logs. Using firstNonNull we can avoid having to painfully consolidate these values, by selecting the first populated field.

choose canonical_user_id from firstNonNull(userId, user_id, user_identifier)

This will produce the following documents:

{
    "canonical_user_id": "123"
},
{
    "canonical_user_id": "456"
},
{
    "canonical_user_id": "789"
}

Now each field has the same name, we have created schema on read consistency.