
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeLooking 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:
count() to count documentslayout_components.is_parent == false)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 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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store