Filter reference by checking if current document exists in array of references

1 replies
Last updated: Feb 5, 2022
I'm currently trying to filter a reference to only show documents that contain the current document's title in one of the referenced document's array objects. So, the `artist document`'s
project
reference object should only show an array of
project
documents where that
artist
has been referenced in the project document's
creditList
(which is an array of references to all artists). This works :
return {
   filter: 'credits[0]->title == $artist',
   params: { artist: document.title },
}
But ideally I can loop through all credits :
credits[]->{title}
and see if any titles match the
document.title
. Is this possible? If so, any tips as to how I might go about doing this?
AI Update

Yes, this is definitely possible! You can use GROQ's array matching capabilities to check if any item in the creditList array references the current artist document.

Instead of checking just the first credit with credits[0]->title == $artist, you can use GROQ's references() function or array matching to check if any credit in the array matches. Here are a couple of approaches:

The cleanest approach is to use GROQ's built-in references() function:

return {
  filter: 'references($artistId)',
  params: { artistId: document._id }
}

This checks if the project document references the current artist's _id anywhere in its structure (including within the creditList array). This is the most performant and idiomatic way to handle reference filtering in Sanity.

Using array matching with the in operator

If you need more specific control or want to match based on title instead of ID, you can use GROQ's array matching:

return {
  filter: '$artist in creditList[]->title',
  params: { artist: document.title }
}

This dereferences all items in creditList (creditList[]->), gets their titles, and checks if the current artist's title is in that array.

Using count with array filtering

Another approach that gives you more explicit control:

return {
  filter: 'count(creditList[@->title == $artist]) > 0',
  params: { artist: document.title }
}

This filters the creditList array to items whose dereferenced title matches, then counts them to ensure at least one match exists.

The references() approach is generally the best choice since it automatically handles checking all reference fields without you needing to specify the exact field path, and it's optimized for performance in Sanity's query engine.

Show original thread
1 reply
$artist in credits[]->title
workedπŸ™‚

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.

Was this answer helpful?