πŸ‘€ Our most exciting product launch yet πŸš€ Join us May 8th for Sanity Connect

GROQ query to find all the different categories of products

By Mohammed Hussam Khatib

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:

  1. *[_type == 'category'] : Find all documents with a type of category.
  2. 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.
  3. [defined(id)]: filter out all the returned data where the nested query is not defined.



Contributor