🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

Learning GROQ and querying in Sanity.io can be confusing, but there are helpful resources available.

3 replies
Last updated: Aug 10, 2021
How would I be able to query that? I'm just learning this and its sort of confusing me
Aug 10, 2021, 2:42 AM
Hi Douglas! I agree that getting started with GROQ can be confusing. Please reach out if you’re interested in some resources—Henrique’s Learn GROQ in 45 Minutes and the Kap & Lauren Learn GROQ video series are two that initially come to mind.
For your query, here’s how I would build it (only the final query is relevant—the rest are just steps to get there—but you should be able to test the intermediary queries in Vision to see what’s returned and infer how you could take the query from there):

• Since queries work left-to-right, you’ll start by getting the documents you want by querying for everything (
*
) that has a
_type
of
post
.
*[_type == post]
• This query will return all the properties that exist on each post, including your array,
categories
. However, each of those
categories
will be an array of
_type
and
_ref
properties. Since you want to see the contents of those
categories
references, you’ll want to access the reference (i.e., “dereference”) using
->
(see these docs for a bit more explanation), and since
categories
is an array, you’ll want to traverse that array (i.e., loop over each array item) using
[]
. There are two ways this can be done—with a projection or with a naked projection —but we’ll only look at the former:
*[_type == 'post'] {
  categories: categories[]->
}
• Hopefully you’re now seeing an array of
post
documents with the dereferenced
categories
data for each. You likely still want the rest of the
post
properties, which we can ask for in the query using the ellipsis operator (
). We put that at the same “level” as the properties we want to return (i.e., as a sibling of
categories
):
*[_type == 'post'] {
  ...,
  categories: categories[]->
}
I hope this helps explain queries a bit. If anything isn’t working or is still confusing, please follow up. Otherwise, have fun building with GROQ and Sanity.
Aug 10, 2021, 3:13 PM
Thank you so much for the comprehensive response.What a phenomenal help!
Aug 10, 2021, 4:16 PM
Thank you so much for the comprehensive response.What a phenomenal help!
Aug 10, 2021, 4:16 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?