How to Filter Query Results by a Property that is a Reference
3 replies
Last updated: Sep 7, 2020
P
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
P
This could be it:
*[_type=="tag" && title == $tag]{
title,
"downloads": *[_type=='download' && references(^._id)] {
title
}
}
Sep 7, 2020, 8:17 AM
H
If you have a document called, for example:
toFilter
that references a set of
tags
that you want to filter by, you could do the following:
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
toFilter
(
*[ _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
*[]
and
[]
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
P
really helpful, thanks
user C
Sep 7, 2020, 10:20 AM
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.