Lesson
4
Functions, in my queries?
Log in to mark your progress for each Lesson and Task
With GROQ you can do more than return values; you can compute and transform them from within the query.
GROQ offers a number of Functions that you can experiment with. These will save you from needing to "post-process" data in your front end or API to shape data as desired from within the query.
Here are a few simple examples:
count()
all the event
documents in the datasetcount(*[_type == "event"])
coalesce()
takes any number of arguments and returns the first one that isn't null
– use it to return the venue
name if defined, otherwise the string "To be confirmed"*[_type == "event" && eventType == "in-person"]{ "venue": coalesce(venue->name, "To be confirmed")}
If you have completed Handling schema changes confidently eventType
might now be named format
– adjust the query above accordingly.
defined()
returns true
for values that are not null
– query only for event
documents that have a headline
artist*[_type == "event" && defined(headline)]
Return an array of unique
headline
artist
names that have upcoming eventsarray::unique( *[ _type == "event" && date > now() && defined(headline) ].headline->name)
This is just scratching the surface! There are functions for geolocation, weighted search, the delta between documents as they change in GROQ webhooks – and more!
The ->
above is resolving a reference. References are a powerful part of Sanity; let's learn how to resolve them in GROQ.
You have 4 uncompleted tasks in this lesson
0 of 4