Filtering arrays in a query and using match for comparison in Sanity.io.
You can filter arrays directly within a GROQ projection using bracket notation with a filter condition. For your case with actors and roles, here's how to do it:
*[_type == 'movie']{
...,
"leadingActors": actors[role == "leading"]
}The key is placing the filter condition [role == "leading"] directly on the array within your projection. This filters the actors array to only include objects where role equals "leading".
Here are more examples showing different filtering scenarios:
// Filter and project specific fields from the filtered array
*[_type == 'movie']{
title,
"leadingActors": actors[role == "leading"]{
name,
role
}
}
// Filter with multiple conditions
*[_type == 'movie']{
"topActors": actors[role == "leading" && experience > 10]
}
// Filter and follow references in the array
*[_type == 'movie']{
"leadActors": actors[role == "leading"].person->{
name,
bio
}
}
// Using match for text filtering
*[_type == 'movie']{
castMembers[characterName match 'Ripley']{
characterName,
person
}
}This is documented in the GROQ Query Cheat Sheet under "Object Projections" - specifically the "Filter embedded objects" example. The filter is applied during projection, so it's efficient and only returns the subset of array elements that match your condition.
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.