Hi @DBA and welcome! 
FQL doesn’t have declaritive syntax like GROUP BY
, rather it works a lot more like a regular programming language. FQL has Map
, Filter
and Reduce
functions.
The way you approach this depends on whether you are focused on either
- fetching a Set of Sellers and also fetching their Orders, or
- fetching a Set of Orders and grouping by Seller
This matters less with your example because you are not filtering on anything, so you effective want everything. But the approach you take will matter if you want to filter on Orders or on Sellers.
Sellers first
This is the easiest. Get all of the Sellers that you want and use Map
to also fetch the orders.
Map(
Paginate(Documents(Collection("Seller"))),
Lambda(
"ref",
Merge(
Get("ref"),
{
data: Merge(
Select("data", Get(Var("ref")),
{
// adds a new `orders` field to Seller.data
orders: Paginate(Match(Index("Order_by_seller"), Var("ref")))
// or whatever you need to do to fetch the particular orders for this seller
}
)
}
)
)
)
Orders first
You can take your Set of Orders that you want (in this case all of them, but you could filter or use an Index here) and use Reduce
to achieve the group by.
I said FQL is a lot more like a regular programming language, so let’s look at an example of a group_by function in javascript and then translate that to FQL.
orders.reduce((result, order) => {
const key = order.seller
const existing_orders = result[key] ?? []
return {
...result,
[key]: [...existing_orders, order]
}
}, {})
Here, we iterate over all of the items in the array and
- determine a key for each item
- if that key exists in the result object, then append the value to that key in the result
- if the key does not exist, add it to the result
We can do something similar in FQL
Reduce(
Lambda(
['result', 'order'],
Let(
{
key: Select(['seller'], Var('order')),
existing_orders: Select(Var('key'), Var('result'), []),
},
Merge(
Var("result"),
ToObject([[Var("key"), Append(Var("order"), Var("existing_orders"))]])
)
)
),
{},
Var('orders')
)
This will return an object that looks like the following, where the keys are the Seller IDs.
{
"355034656429572182": [
{ /* order1 ... */ },
{ /* order2 ... */ },
],
"333736995637428290": [
{ /* order1 ... */ },
],
"312254774755983424": [
{ /* order1 ... */ },
{ /* order2 ... */ },
{ /* order3 ... */ },
]
}
You can transform that however you like. ToArray
and ToObject
are helpful FQL functions for manipulating objects with arbitrary keys.