Comparing arrays in GROQ query to find intersections.
For checking if two arrays have at least one intersection (overlapping value), you can use the count() function combined with the @ filter operator in GROQ. Here's the pattern:
count(array1[@ in array2]) > 0So if you have a field allCheckinIds and a parameter $userIds, you'd write:
count(allCheckinIds[@ in $userIds]) > 0This works by:
- Taking the first array (
allCheckinIds) - Filtering it with
[@ in $userIds]- the@represents each element in the array, and checks if it exists in the second array - Counting how many matches were found
- Checking if that count is greater than 0
You can use this in a filter to find documents that have at least one matching value:
*[_type == "yourType" && count(allCheckinIds[@ in $userIds]) > 0]This is a clever workaround since GROQ doesn't have a built-in array intersection operator. The technique comes from this community discussion where the same question was asked.
If you need to pass userIds as a parameter (which is common when querying from your application), you'd use it like this with the JS client:
client.fetch(
`*[_type == "yourType" && count(allCheckinIds[@ in $userIds]) > 0]`,
{ userIds: ['id1', 'id2', 'id3'] }
)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.