Filter reference by checking if current document exists in array of references
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:
Using the references() function (Recommended)
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 thread1 reply
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.