👀 See Sanity in action: Watch product demo now →

How to Filter Query Results by a Property that is a Reference

3 replies
Last updated: Sep 7, 2020
Hi, I was wondering how I could filter query results by a property that is a reference? i.e. i have X amount of “downloads” and want to filter them by a given “tag”. “tags” is an array of references.
Sep 7, 2020, 7:56 AM
This could be it:
*[_type=="tag" && title == $tag]{
  "downloads": *[_type=='download' && references(^._id)] {

Sep 7, 2020, 8:17 AM
If you have a document called, for example:
that references a set of
that you want to filter by, you could do the following:

*[_type=="toFilter"] {..., tags-> } [tags.name ==$nameOfTagToFilterBy] 
This uses the ability of GROQ to chain arbitrarily many
[ ]
( filter-by truth-value of contents ) and
( get these properties from the result-set ), by first getting every document of type
*[ _type == "toFilter]
), then expanding the references while keeping every field (
{ ..., tags->}
) and then filtering the resulting array of documents by properties on the now expanded tag-field (
[tags.name == $nameOfTagToFilterBy]
Note the difference between
here. The
means “give me EVERY document, and then filter by them by the contents of my
“, while
alone means “for the documents I already have from prior filters, filter them further by these contents”.
Does that help?
Sep 7, 2020, 9:30 AM
really helpful, thanks
user C
Sep 7, 2020, 10:20 AM

Sanity.io – build remarkable experiences at scale

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

Categorized in