Unlock seamless workflows and faster delivery with our latest releases – get the details

Is it possible to fetch more than one "_type" using GROQ?

4 replies
Last updated: Nov 2, 2020
Hey - been stuck with my head in the sanity/next.js documentation for quite som time now and can't seem to find the answer that i'm looking for... But does anyone of you guys know, if it's possible to fetch more than one "_type" using GROQ? Let's say that i have a schema for my "frontpage" and my "blog-post" and i want to display them on the same page? This seems so easy with Graphql but i'm really struggling to wrap my head around how i'm supposed to do it in GROQ?
Thanks in advance
🙂
Nov 2, 2020, 10:01 AM
Hi Morgan! You can fetch multiple document types as follows:
*[_type in ["frontpage", "blogPost"]]
Nov 2, 2020, 10:06 AM
you might get weird results though if you have fields with the same name but different type.
Nov 2, 2020, 10:22 AM
That’s a great point Arjen! To prevent that from happening, you can specify projections for the different types, e.g.:
*[_type in ["frontpage", "blogPost"]]{
  _type == "frontpage" => {
    // Your field selection for the frontpage type
  },
  _type == "blogPost" => {
    // Your field selection for the blogPost type
  }
}
Nov 2, 2020, 10:27 AM
Wow thanks, both of you!
Nov 2, 2020, 10:28 AM

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?