Using arrays in Groq queries with Next.js and Sanity.io
Hey! Great question about using arrays in GROQ queries.
To check if a gender field matches any value in your array of strings, you can use the in operator in GROQ. Here's how:
*[gender in ["male", "female"]]How it works:
The in operator checks if the left-hand value (your gender field) matches any element in the right-hand array. It compares for equality with each element and returns true as soon as it finds a match.
Important note about variables:
GROQ doesn't support JavaScript variables directly in queries. If you have a JavaScript array like const str = ['male', 'female'], you'll need to construct the query string dynamically:
const str = ['male', 'female'];
const query = `*[gender in ${JSON.stringify(str)}]`;This constructs: *[gender in ["male","female"]]
More examples:
// Basic usage
*[gender in ["male", "female"]]
// Combined with other filters
*[_type == "person" && gender in ["male", "female"]]
// With projection
*[gender in ["male", "female"]] {
name,
gender,
age
}For the opposite (NOT in): If you want to find documents where gender is NOT in your array:
*[!(gender in ["male", "female"])]The in operator is really handy for this kind of filtering - it's much cleaner than chaining multiple OR conditions!
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.