👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Ordering Celebs by their most recently updated facts in Sanity.io

12 replies
Last updated: Jun 10, 2022
Hi! I'd like to know how to order values by a referenced field.
I have the document type
celeb
. And the document type
fact
. Each
fact
references a
celeb
. I want to list
celebs
ordered by their most recently updated
facts
. So I want to get a list of
celebs
where the
celeb
that just had a
fact
added about them would show up at the top.
I also posted this question on Stackoverflow to keep a record of the answer
https://stackoverflow.com/questions/72564416/sanity-groq-order-by-the-value-of-a-referenced-field
Jun 9, 2022, 5:37 PM
Hi!
I think something along the lines of this should work:


*[_type == 'celeb']{
 ...,
 "latestFact": *[_type == 'fact' && references(^._id)] | order(_updatedAt)[0]._updatedAt
}| order(latestFact)
Jun 10, 2022, 2:09 PM
Hi! Something like:
*[_type == "celeb"] {
  _id,
  name,
  "latestFact": *[_type == "fact" && celeb._ref == ^._id] | order(_updatedAt desc)[0]
}
  | order(latestFact._updatedAt desc)
This assumes that each
fact
has a field called
celeb
which is a ref to the celeb document.
For each celeb, it finds the latest fact. At the end, it sorts all the celebs by the date.
Jun 10, 2022, 2:09 PM
hah!
user L
Jun 10, 2022, 2:10 PM
Comment race condition 😁
Jun 10, 2022, 2:10 PM
The difference between these two answers is that Jørn’s will just fetch the latest timestamp, while mine will include the latest fact.
Jun 10, 2022, 2:13 PM
A slightly different approach if you ever needed a third one 😄 GROQ is flexible. This one doesn't require a sub-query, although it does reorder your facts. You can work around that if needed:
*[_type == "celeb"]{
  facts[]-> | order(_updatedAt desc)
} | order(facts[0]._updatedAt)
Jun 10, 2022, 2:26 PM
user M
That can be a good solution if celebs have a
facts
field; I assumed they didn’t. Also note that this will fetch all facts for each celeb first, even though only the first one is needed to sort. A subquery like this:
*[_type == "fact" && celeb._ref == ^._id] | order(_updatedAt desc)[0]
…will only need to fetch the newest fact for each celeb.
Jun 10, 2022, 2:30 PM
Ah, good catch! I read it the other way around indeed: that a
celeb
references a
fact
. Please disregard the above 🙂
Jun 10, 2022, 2:34 PM
poweranger
Jun 10, 2022, 3:10 PM
user S
any more questions 😅
Jun 10, 2022, 3:11 PM
So much brain power went into answering my question! Thanks everyone, very appreciated!
Jun 10, 2022, 3:33 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?