Filter child elements in Sanity query (documents array references)
Yes, it is possible to filter child elements in a GROQ query! You can use a filter inside the array projection to only include documents that meet your criteria.
For your example where you want to return only documents where deleted != true, you can do this:
*[_type == "event"] {
_id,
_key,
documents[deleted != true] -> {
...
}
}The key is placing the filter [deleted != true] directly after the documents array field and before the dereferencing operator ->.
How it works
When you use square brackets [] after an array field, you're telling GROQ to traverse the array. By adding a filter expression inside those brackets, you filter which elements from the array should be included before dereferencing them.
More examples
You can use various filter conditions:
// Filter by a specific value
documents[status == "active"] -> { ... }
// Filter by existence of a field
documents[defined(publishedAt)] -> { ... }
// Combine multiple conditions
documents[deleted != true && status == "published"] -> { ... }
// Filter by array membership
documents[category in ["news", "blog"]] -> { ... }Important note
The blank filter [] is required when working with arrays of references. As mentioned in the Sanity documentation on expanding array references, you must use square brackets to traverse the array before dereferencing, so adding your filter condition inside those brackets is the natural way to filter the results.
Show original thread8 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.