Query array object fields by type in Sanity GROQ
Unfortunately, GROQ doesn't have a built-in way to dynamically filter object properties by their schema type. GROQ operates on the actual data values in your documents, not on the schema metadata itself, so there's no getFields() function or ability to introspect which fields were defined as type: "string" in your schema definition.
Why this doesn't work:
GROQ queries run against your stored data, not your schema definitions. When you query, GROQ only sees the actual values in your documents—it has no knowledge that a particular field was defined as a string type versus a slug type in your schema. There's no type() function that can inspect schema metadata or determine the original type definition.
What you can do instead:
Since you need to be explicit, here are your options:
- Manually project the string fields you want:
*[_type == "exampleSchema"] {
objects[] {
title,
randomString,
name,
evenMoreRandomString
}
}- Use conditional projections based on object type:
If the different object types in your array have different string fields:
*[_type == "exampleSchema"] {
objects[] {
_type == "object" => {
title,
randomString
},
_type == "objectTwo" => {
name,
evenMoreRandomString
}
}
}- Get all fields with the spread operator:
If you want everything from the objects:
*[_type == "exampleSchema"] {
objects[] {
...
}
}This gets you all fields including the url slugs. You'd then need to filter out non-string fields in your application code where you have access to your schema definitions.
- Filter in application code:
If you truly need dynamic type-based filtering, the most practical approach is to fetch all the data and filter it in your application where you have access to both the schema definitions and the data. You could create a helper function that knows your schema and filters out non-string fields.
The bottom line: GROQ is designed for querying content data, not for introspecting schema metadata, so you'll need to explicitly specify which fields you want in your projections or handle the filtering in your application layer where you have access to your schema definitions.
Show original thread3 replies
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.