GROQ query to expand references and filter
This is useful to pre-filter references, or count references based on a query like status == 'active'.
Query
*[_type == 'collection'] {
"numTotalProducts": count(products),
"numActiveProducts": count((products[]->store.status)[@ == 'active'])
}In the query above, `products` is an array of references. Therefore, you need to expand them to filter through them.
I've discovered that wrapping a section that expands a reference in parentheses, allows you to filter using regular GROQ brackets. This is not mentioned in the documentation, so I thought I'd share this as a snippet.
Not working: `products[]->store.status[@ == 'active']`
When you query this, you'll find an array is returned with `[null, null, null]`.
Working: `(products[]->store.status)[@ == 'active']`
This will return a properly filtered array of `['active', 'active']`. I use that to `count` the number of active products.