Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

How to request and filter documents in Sanity.io using GROQ queries.

9 replies
Last updated: Dec 27, 2021
Is there a way to request all documents from a type (drafts + published) and for each document filter by1. if there is a draft version of the document it and remove the published one (from the results)
2. if there isn't a draft version, return the published document
In preview mode, I'd like to not have duplicates of documents in listing sections. Do I have to do this after the request? Or is it possible to do it inside the GROQ query?
Dec 27, 2021, 9:39 AM
Hi User. You could try an approach like this, which should give you an array of `_id`s.

{
  'drafts': *[ _type in ['documentType1', 'documentType2'] && _id in path("drafts.**") ]._id,
  'published': *[ _type in ['documentType1', 'documentType2'] && !(_id in path("drafts.**"))]._id,
}
{
  'current': published[ !("drafts." + @ in ^.drafts) ] + drafts
}
You originally said “all documents,” so you
could remove the
_type in […]
part, though that’ll return image assets, system documents, etc. as well.
Dec 27, 2021, 3:21 PM
Sorry, I meant all documents from a specific type, I forgot the precision.
Dec 27, 2021, 3:25 PM
No problem! In that case, the above should work. You can simplify it to
_type == 'specificType'
in the
drafts
and
published
filters.
Dec 27, 2021, 3:26 PM
Wow I wasn't aware of this GROQ feature to chain objects and use them in one request!Is it mentioned in docs?
Dec 27, 2021, 3:26 PM
No problem! In that case, the above should work. You can simplify it to
_type == 'specificType'
in the
drafts
and
published
filters.
Dec 27, 2021, 3:26 PM
I thought there were docs on it, but you’re right—I can’t find anything. User and User mentioned it in this blog post and User used it in this schema . I’ll add something to the docs later today.
Dec 27, 2021, 3:34 PM
I though there were docs on it, but I suppose not. User and User mentioned it in this blog post and User used it in this schema . I’ll add something to the docs later today.
Dec 27, 2021, 3:34 PM
I thought I missed this nice feature but hard to find it if it's not in the docs ^^Thanks for the answer
👍
Dec 27, 2021, 3:46 PM
I thought I missed this nice feature but hard to find it if it's not in the docs ^^Thanks for the answer
👍
Dec 27, 2021, 3:46 PM

Sanity– build remarkable experiences at scale

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

Was this answer helpful?