TracksMastering Content OperationsCoursesBetween GROQ and a hard placeJoins and subqueries
Between GROQ and a hard place
Markdown Version

Joins and subqueries

Log in to watch a video walkthrough of this lesson
Log in
Video thumbnail
When a document contains a reference it only stores the ID of that document, GROQ can resolve it
Log in to mark your progress for each Lesson and Task

Try querying for an event document and return the venue reference.

Return the venue of every event
*[_type == "event" && defined(venue)][0]{
venue
}

The venue attribute will return a reference to another document's ID in the attribute _ref.

You can “resolve” this reference with this operator ->

This deceptively simple operator will perform a “sub-query” to resolve the document with that _id.

Resolve the venue reference
*[_type == "event" && defined(venue)][0]{
venue->
}

Excellent! We now have the actual details of the category document. But again, we have the “too much data” problem. This can be fixed by adding an additional projection.

Get only the name of the venue document
*[_type == "event" && defined(venue)][0]{
venue->{
name
}
}

It’s possible to create your own subquery anywhere in a document. However, you should be mindful that additional nesting and queries can increase response time and the volume of data. Exercise caution.

References are one-way in that they are stored on a document. However the references() GROQ function allows you to look up all other references to a document ID.

A useful sub-query for this project would be to look up every event when querying for an artist, like a reverse lookup of references.

Using the references() GROQ function, get every event featuring the current artist.
*[_type == "artist"][0]{
name,
"events": *[_type == "event" && references(^._id)]{
name
}
}

The ^ character traverses out of the current filter to access the "parent." In the above example, it is accessing the _id attribute of the artist document.

See GROQ operators in the documentation for more details on what is available when writing GROQ queries
See High Performance GROQ for more guidance on keeping queries performant
You have 4 uncompleted tasks in this lesson
0 of 4