Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

How to write a query that filters articles by the value of a referenced document in Sanity.io

9 replies
Last updated: Feb 9, 2021
Hi all, i'm a little confused as to how to write a query that filters by the value of a referenced document. In my case, I have an
article
document type, within it an array of references to
tag
documents.
tag
docs have a unique slug. I'd like to get all articles that are tagged with
tag-a
and
tag-b
.
If I hard-code the refs for these tags, I can do it this way:


*[
  _type == "article"
  && tags[]._ref in ["518a1ceb-b5f2-4227-bfa2-42a39c723189", "3b2e74c0-7163-43db-a9d1-0fcf80969272"]
]{
  ...
}
But, I'm not sure how to do this by querying for the tag slug. Something like this:


*[
  _type == "article"
  && tags[]._ref in [*[_type == 'tag' && slug in ['tag-a', 'tag-b']]._id]
]{
  ...
}
Feb 8, 2021, 7:55 PM
Hi Joseph. This might need some work but could you give it a try?

*[_type == "article" && tags[]->slug.current match ["tag-a", "tag-b"]]
Feb 8, 2021, 8:19 PM
Thanks Geoff, that might be it. Unfortunately I'm working with an enormous dataset (there are 27k tags, i'm not sure how that happened), so this request times out
Feb 8, 2021, 9:03 PM
Ok, i just tried this on our more manageable staging dataset. From what I recall, the
match
operator requires matching all the tags, I think I want to use
in
. This works:

*[
  _type == "article"
  && tags[]->slug match ["tag-a"]
]{
  title,
  tags[]->,
}[0..5]
Feb 8, 2021, 9:06 PM
This returns 0 results:
*[
  _type == "article"
  && tags[]->slug match ["tag-a", "tag-b"]
]{
  title,
  tags[]->,
}[0..5]
Feb 8, 2021, 9:06 PM
This gives me an error:
*[
  _type == "article"
  && tags[]->slug in ["tag-a", "tag-b"]
]{
  tags[]->,
}[0..5]
Feb 8, 2021, 9:08 PM
Query error
No function in() defined for arguments (array, array)

Feb 8, 2021, 9:08 PM
Sorry Joseph. My fault for misunderstanding. If you want to match
tag-a
or
tag-b
, can you see if this works?

*[_type == "article" && tags[]->slug.current match ["tag-a"] || tags[]->slug.current match ["tag-b"]]
I’ve given that a try on one of my schemas that I think resemble yours, but if I’ve missed the mark once more, my apologies.
Feb 8, 2021, 11:57 PM
No worries, I wasn't clear on my search being an "Or" situation. this does the trick, thank you!
Feb 9, 2021, 12:24 AM
Oh good! Thanks Joseph!
Feb 9, 2021, 12:54 AM

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?