This example script has a misconception about the time and the place in which the script runs.
Scripts inside the aggregation tree are given a single document to evaluate on a single shard. The scripts can inspect the fields of that doc but that's the scope of the context it works in. It works in the data-gathering phase on data nodes.
In contrast, the "cardinality" value is a final result value only available after all matching docs have been examined on all shards and returned to a central coordinating node.
To perform any reasoning about final aggregation results on the coordinating node you need to use a pipeline aggregation such as thebucket selector