How to query nested document references in array by slug in Sanity?

3 replies
Last updated: Jun 13, 2023
If these are my schemas:
footerMenu(document)
   columns(array) of:
      terms(document)
      help(document)

terms(document)
   title
   slug
   ...

help(document)
   title
   slug
   ...
How can I query to get the columns of footerMenu whose slug == "some-slug".

I'm trying something like:

*[_type == "footerMenu"] {
  columns[] {
     "item": *[slug.current == "some-slug"] 
  }
}
But it is clearly wrong.
Thank you!
AI Update

Based on your schema structure, you need to filter the columns array to only include items where the referenced document's slug matches "some-slug". Here's how to do it:

*[_type == "footerMenu"][0] {
  "columns": columns[]->[ slug.current == "some-slug" ]
}

Let me break down what's happening:

  1. **columns[]-> ** - This dereferences the references in your columns array, converting them from {_ref: "document-id"} to the actual document data
  2. [slug.current == "some-slug"] - This filters the dereferenced array to only include documents where the slug matches

If you want to get all the fields from the matching column documents, you can add a projection:

*[_type == "footerMenu"][0] {
  "columns": columns[]->[ slug.current == "some-slug" ] {
    _id,
    _type,
    title,
    slug
  }
}

Or if you want to preserve the entire footerMenu structure but only with filtered columns:

*[_type == "footerMenu"][0] {
  ...,
  "columns": columns[]->[ slug.current == "some-slug" ]
}

The key difference from your attempt is that you need to dereference first with -> and then filter with [condition], rather than trying to use a subquery with *[...] inside the projection. The reference access operator (->) handles the join for you automatically by internally executing a subquery to fetch the referenced documents.

Show original thread
3 replies
If I’m understanding correctly, maybe something like this:
*[_type == "footerMenu"] {
  columns[@.slug.current == "some-slug"]
}
That was exactly what I was looking for! Thank you so much, rd : )
You’re welcome!

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?