Structured Content 2022: Join our conference to explore fresh perspectives on content and digital experiences →

is it possible to filter child elements in a query? e.g. in the query below I’d like to return only documents where `deleted != true` ```*[_type == "event"] { _id,...

8 replies
Last updated: Jan 4, 2021

is it possible to filter child elements in a query? e.g. in the query below I’d like to return only documents where

deleted != true

*[_type == "event"] {
      _id,
      _key,
      documents[] -> {
        ...
      }
    } 

Jan 4, 2021, 12:06 PM

Is

documents
 an array of references in this case?

Jan 4, 2021, 12:10 PM

yes

user Y

Jan 4, 2021, 12:11 PM

Then

*[_type == "event"] {
      _id,
      _key,
      documents[]->[deleted != true]{
        ...
      }
    }
should work, but will return
documents: []
 where no documents match the filter criteria

Jan 4, 2021, 12:15 PM

works like a charm, much appreciated

user Y

Jan 4, 2021, 12:16 PM

If you want to return nothing, this might work:

*[_type == "event"]{
  _id,
  _key, // there shouldn't be a _key in a document?
  "documents": 
  	select(
    	count(
      	documents[]->[deleted != true]
	  	) > 0 => documents[]->[deleted != true]{...}
	)
}

Jan 4, 2021, 12:17 PM

empty array is totally fine in this case but cool to see these advanced queries! is there any expanded query cheatsheet where these advanced usage examples might live?

Jan 4, 2021, 12:20 PM

Not at the moment, so you'll have to dig in the reference docs to find it 🙂 We totally should build out the cheatsheet though

Jan 4, 2021, 12:20 PM

definitely! it’s already great but there’s so much more to be done with sanity. i’m sure it would save you a lot of time too 😏

Jan 4, 2021, 12:36 PM

Sanity.io: Get the most out of your content

Sanity.io is a platform to build websites and applications. It comes with great APIs that let you treat content like data. Give your team exactly what they need to edit and publish their content with the customizable Sanity Studio. Get real-time collaboration out of the box. Sanity.io comes with a hosted datastore for JSON documents, query languages like GROQ and GraphQL, CDNs, on-demand asset transformations, presentation agnostic rich text, plugins, and much more.

Don't compromise on developer experience. Join thousands of developers and trusted companies and power your content with Sanity.io. Free to get started, pay-as-you-go on all plans.