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

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.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.