what is the recommended way to query an array of references?

3 replies
Last updated: Oct 11, 2020
what is the recommended way to query an array of references? For example right now I have a field
articles
of type array of elements with type
article
and right now I'm doing this:
	articles[]{
		'article': @->
	}
but it forces me to have everything nested under
article
which I'd like to avoid if possible
AI Update

You're almost there! Instead of using @-> with an alias, you can dereference the array directly:

articles[]->

This will give you the full referenced article documents directly in the array without any extra nesting.

Your current query:

articles[]{
  'article': @->
}

creates objects with an article property because you're explicitly projecting into that structure. The @ operator refers to the current element, and by wrapping it with 'article': @->, you're creating that nested object.

By using articles[]->, you're telling GROQ to:

  1. Iterate through the articles array ([])
  2. Dereference each reference (->)
  3. Return the dereferenced documents directly

If you want to select specific fields from the referenced articles, you can also project within the dereference:

articles[]->{
  title,
  slug,
  publishedAt
}

This gives you an array of article objects with only the fields you specify, still without the extra nesting level.

The reference access operator works seamlessly with array projections - when you use -> on an array of references, it automatically dereferences all items in that array. This is the standard pattern for working with arrays of references in GROQ queries.

Show original thread
3 replies
	articles[]->{
	  ...
	}
This will do the trick
😀
	articles[]->{
	  ...
	}
This will do the trick
😀
thanks! knew there had to be a concise solution there 🙂

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?