Create a count for related items using GROQ

Tuesday, October 25, 2022

I'm using the count() function of GROQ queries to display the number of posts for a tag on my tags page, but it can be used for anything that would have a varying number of items.

To count items using GROQ is as simple as using the count() function.

1{
2  // Get an array of all completed items
3  "items": *[completed == true] 
4} | {
5  // use count function to count the key
6  "count": count(items) 
7}
8
9// => { "count": 90 }

Of course this can be reduced to a single query:

1{
2  // Get an array of all completed items and count them
3  // use count function to count the key
4  "count": count(*[completed == true] ) 
5}
6
7// => { "count": 90 }

This can also be done with any field, including references which we can do like so:

1*[_type == "tag" ]{
2   // Get all items that reference the current tag
3   "refs": *[references(^._id)] {}
4 } | {
5   // count each reference
6   "count": count(refs)
7 }[count > 0] //filter out tags with 0 referenced items

Again, this can be shortened to a single query:

1*[_type == "tag" ]{
2   // Get all items that reference the current tag and count them
3   "count": count(*[references(^._id)])
4 }[count > 0] //filter out tags with 0 referenced items

Other posts


Tagged with: