✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

Filtering arrays in a query and using match for comparison in Sanity.io.

5 replies
Last updated: Nov 11, 2023
Hi all, how can I filter out an array returned from a query?I have a query similar to this one

*[_type == 'movie']{..., actors}
where actors is an array of objects containing the role (
leading
,
support
, etc) and the reference to the actor. I need to filter out the actors array to only include ones in a leading role.
Nov 11, 2023, 3:40 PM
It sounds like you’ll be able to use the array filter syntax for this:

*[_type == 'movie']{
  ...,
  actors[leading == true], // or maybe...
  // actors[role == 'leading'],
}
Nov 11, 2023, 4:43 PM
Thanks, I don't know what I was doing wrong but I couldn't get it to work as I wanted... But hey, it works now ✌️
Nov 11, 2023, 7:18 PM
And if I wanted all artists named "James" it would be something like this right?

*[_type == 'movie']{
  actors[actor->name == 'James'],
}
Assuming
actors
has this shape:
actors: [
  {
    role: string,
    actor: reference,
  },
  // ...
]
Nov 11, 2023, 7:20 PM
Yes, if the
name
property is literally just James, then that should work. If it’s their full name or you want to do basic matching, you may want to consider using match rather than
==
.
Nov 11, 2023, 7:58 PM
Yup, I'm familiar with it. In this case it would be a full comparison rather than a partial match. Thanks again!
Nov 11, 2023, 9:31 PM

Sanity– build remarkable experiences at scale

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

Was this answer helpful?