How to get the number of nested/children components in a GROQ query.
Looking at your GROQ query, you want to count how many child components each parent component has. Based on the count() function documentation, you can use count() with a filter to count references.
Here's how to modify your query to add a count of children to each parent component:
{
template,
layout_library {
hero_title,
components_section_title,
'items': *[_type == 'components' && layout_components.is_parent == true] | order(title asc){
title,
_id,
slug,
layout_components {
component_image${imageQuery},
},
'childrenCount': count(*[_type == 'components' && layout_components.is_parent == false && references(^._id)])
},
'children': *[_type == 'components' && layout_components.is_parent == false] | order(title asc){
title,
_id,
// other fields you need
},
},
}The key part is 'childrenCount': count(*[_type == 'components' && layout_components.is_parent == false && references(^._id)]). This:
- Uses
count()to count documents - Filters for child components (
layout_components.is_parent == false) - Uses
references(^._id)to find components that reference the current parent (the^accesses the parent scope's_id)
This assumes your child components have a reference field pointing to their parent. If your relationship structure is different (like if parents have an array of child references), you'd adjust accordingly:
'childrenCount': count(childReferencesArray)If you need to count children based on a different relationship structure, let me know how your parent-child relationship is defined in your schema and I can adjust the solution!
Sanity ā Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.