🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

Sanity GROQ Filter category by highest reference count in other documents

By Surjith S M

A short snippet to filter category, tags or other document based on total referenced count.

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

Other schemas by author