Sanity GROQ Filter category by highest reference count in other documents
A short snippet to filter category, tags or other document based on total referenced count.
By Surjith S M
groq.js
*[_type == "category"] {
...,
"count": count(*[_type == "post" && references(^._id)])
} | order(count desc) [0...10]This snippet first get the data from category and then fetches count based on references(^._id) and finally sort desc based on the count.
See:
https://www.sanity.io/docs/groq-functions#5759ed6ff047
https://www.sanity.io/docs/query-cheat-sheet#1ca403b172cb
Contributor

Surjith S M
Web Designer & Front-end Developer. Figma, TailwindCSS & Next.js
India