Using the Object.values() and flatMap() functions in v10 UDFs

To transform an array of objects like this:

[
    {
      allergens: ["foo","bar"],
      potential_allergens: []
    },
    {
      allergens: [],
      potential_allergens: ["loco"]
    },
    // ...
]

to a single array like this:

[
    "foo",
    "bar",
    "loco",
    ...
]

You can use the FQL fold method.

If you are familiar with Javascript, FQL’s fold method functions the same as Javascript’s reduce method without a seed value. FQL provides the separate fold method which works like Javascript’s reduce method with a seed value.

You might try something like this:

RawIngredient.allAllergens()
  .fold([], (acc, val) => acc.concat(val.allergens).concat(val.potential_allergens))
  .distinct()

Note that reduce and fold are “greedy” methods. They will attempt to read the ENTIRE set before computing a result. This makes it impractical to use with large and/or unbounded sets.

Fauna is optimized for operational workloads (it’s an OLTP database), not analytics (Not an OLAP database). If you need to scale the Allergens collection and efficiently fetch the list of all distinct values, then you may need to consider denormalizing or precomputing and saving the list, updating it as changes are made.

As the dataset grows to large for Fauna to compute within a single query, you can paginate through all of the documents, loading the data locally in the client, and calculating the distinct list of values there.