GROQ: Filter blog posts by referenced tag names
I can help you filter your blog posts by referenced tag names! The key is understanding how to query through references in GROQ arrays.
Your commented-out filter is close, but needs a slight adjustment. Here are the working approaches:
Option 1: Using the in operator (recommended)
*[_type == "post" && "Tutorial" in tags[]->tag]
{
'slug': slug.current,
title,
'date': _createdAt,
subtitle,
'tags': tags[]->{tag, 'color': tagColor.hex, description, 'slug': slug.current},
}
| order(_createdAt desc)The in operator checks if "Tutorial" exists anywhere in the array of dereferenced tag names. This is the most readable and performant approach.
Option 2: Using count() for existence check
*[_type == "post" && count(tags[tag == "Tutorial"]) > 0]This filters the tags array first, then checks if any matches exist.
For multiple tag filters:
If you want posts that have ANY of several tags (OR logic):
*[_type == "post" && count(tags[]->tag in ["Tutorial", "Guide", "How-to"]) > 0]If you want posts that have ALL specified tags (AND logic):
*[_type == "post"
&& "Tutorial" in tags[]->tag
&& "Advanced" in tags[]->tag
]The -> operator dereferences the tag document, and then you can access its fields like tag. The [] after tags means "for all items in this array," so tags[]->tag gives you an array of all tag names from the referenced documents.
According to the query optimization documentation, it's best practice to filter as early as possible in your query pipeline, which is exactly what you're doing by putting this condition in your initial filter. This approach ensures better performance as your dataset grows.
Show original thread6 replies
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.