👀 See Sanity in action: Watch product demo now →

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 – build remarkable experiences at scale

Sanity is a customizable solution that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Categorized in