Skip to content

Create a count for related items using GROQ

Oct 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.

{
  // Get an array of all completed items
  "items": *[completed == true] 
} | {
  // use count function to count the key
  "count": count(items) 
}

// => { "count": 90 }

Of course this can be reduced to a single query:

{
  // Get an array of all completed items and count them
  // use count function to count the key
  "count": count(*[completed == true] ) 
}

// => { "count": 90 }

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

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

Again, this can be shortened to a single query:

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