If you want to group posts by category, you can do that in your query by using joins and the special references variable:
*[_type == 'category'] {
...,
"posts": *[_type == 'post' && references(^._id)]
}
Here we are querying the category documents first *[_type == 'category']
then for each category
projection we are querying for all post
documents that references this category by id
: *[_type == 'post' && references(^._id)]
. The ^
parent operator refers the parent document, in this case the category
document.
For more details you can check this link from the official docs.
I hope this helps