Go Behind the Experience to see how Tecovas brings the West to life with Sanity 🤠 July 18th

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
. And the document type
. Each
references a
. I want to list
ordered by their most recently updated
. So I want to get a list of
where the
that just had a
added about them would show up at the top.
I also posted this question on Stackoverflow to keep a record of the answer
Jun 9, 2022, 5:37 PM
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"] {
  "latestFact": *[_type == "fact" && celeb._ref == ^._id] | order(_updatedAt desc)[0]
  | order(latestFact._updatedAt desc)
This assumes that each
has a field called
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
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
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
references a
. Please disregard the above 🙂
Jun 10, 2022, 2:34 PM
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?