👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

Filter Blog Post Query Based on Referenced Tag Names

6 replies
Last updated: Apr 13, 2021
Hello, I am trying to work with GROQ to get some information.For each of my "blog post" document types, there are 3 "tag" document types referenced. I would like to filter my "blog post" query based on its referenced "tag" names. (edited) 
If anyone has any ideas on how I might make this work, I'm all ears. Here is my current implementation:

*[_type == "post"] // && tags[]->tag == "Tutorial" (this doesn't work)
{
  'slug': slug.current, 
  title, 
  'date': _createdAt, 
  subtitle,
  'tags': tags[]->{tag, 'color': tagColor.hex, description, 'slug': slug.current},
} 
| order(_createdAt desc)
I posted in
groq but still haven't gotten any feedback
Apr 13, 2021, 2:41 PM
For checking against arrays, it's best to use the
in
operator.
Something like this might be what you're looking for (I typically would key off of the _id instead of the tag string, but the tag string is nicely readable)


*[_type == "post" && "Tutorial" in tags[]->tag]

Apr 13, 2021, 2:59 PM
That will see if the string "Tutorial" is in the array that's generated by tags[]->tag (which will be an array of all the tag strings).
If you use the id instead (which will protect agains the tag string changing), you'd modify the filter to look more like this

*[_type == "post" && "some-long-id-string" in tags[]._ref]
(you'd no longer need to "de-reference" the tags, since the
_ref
matches the Tag document ID
Apr 13, 2021, 3:02 PM
For checking against arrays, it's best to use the
in
operator.
Something like this might be what you're looking for (I typically would key off of the _id instead of the tag string, but the tag string is nicely readable)


*[_type == "post" && "Tutorial" in tags[]->tag]

Apr 13, 2021, 2:59 PM
user T
oh i see! i was essentially trying to compare two arrays. so is there a way to check if multiple tags match like
["Tutorial", "Azure"] in tags[]->tag
Apr 13, 2021, 4:08 PM
Unfortunately, there's no array intersections, so the syntax would be:
("Tutorial" in tags[]->tag || "Azure" in tags[]->tag) // OR
("Tutorial" in tags[]->tag && "Azure" in tags[]->tag) // AND
Depending on if you want AND or OR
Apr 13, 2021, 5:28 PM
Thank you!!
Apr 13, 2021, 6:11 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?