CoursesBetween GROQ and a hard placeJoins and subqueries
Certification
Sanity developer certification
Track
Sanity developer essentials

Between GROQ and a hard place

Lesson
5

Joins and subqueries

For documents with references, by default, all you'll return is the _id of that referenced document.
Log in to mark your progress for each Lesson and Task
Return the venue of every event
*[_type == "event" && defined(venue)]{
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)]{
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)]{
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.

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"]{
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 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