How to get the title of a referenced document while keeping all other data in GROQ.
You can use the dereferencing operator (->) in GROQ to get the title of a referenced document while keeping all your other data. For your case with images that have tags referencing collections, you'll want to dereference the references within the array.
Here's how to structure your query:
*[_type == 'image']{
...,
tags[]->{
title
}
}Let me break down what's happening:
...- The ellipsis operator keeps all existing fields from your image documentstags[]- The square brackets traverse the array of tags->- The dereferencing operator follows each reference to get the actual collection document{title}- This projection extracts just the title from each collection
This will give you something like:
[
{
_id: "image-1",
url: "...",
// all your other image fields
tags: [
{ title: "Collection A" },
{ title: "Collection B" }
]
}
]If you want just the collection titles as a flat array of strings instead of objects, you can use a naked projection:
*[_type == 'image']{
...,
tags[]->title
}This would give you:
{
tags: ["Collection A", "Collection B"]
}The key points:
- Use
[]to traverse arrays of references - Use
->to dereference (follow) the reference - Use
{title}to project just the fields you want, or.titlefor a naked projection to get just the values
You can read more about this in the GROQ documentation on expanding references.
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.