GROQ query to find all the different categories of products
categories.js
[_type == 'category']{
title,
'id':*[defined(categories) && _type == 'product' && references(^._id)][0]{
_id
}
}[defined(id)]This GROQ query can be used to list out all categories of a product and filter out the categories of which there exist no product of that particular category.
This is using the default schema of Next.js E-commerce
Explanation of the query:
*[_type == 'category']: Find all documents with a type of category.- retrieve the category title and perform a nested query which joins all products which references
_id.If there exist atleast a single output through this query , it means there exist atleast a single product with that category. [defined(id)]: filter out all the returned data where the nested query is not defined.
Contributor

Mohammed Hussam Khatib
Frontend developer | student
India