Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

215
Views
Sanity.io GROQ - Retrive document by highest reference count in other documents

I have a tag document that looks like

{
  name: 'tag',
  title: 'Tag',
  type: 'document',
  fields: [
    {
      name: 'label',
      title: 'Label',
      type: 'string',
    }
  ]
}

And page document that looks like

{
  name: "page",
  title: "Page",
  type: "document",
  fields: [
    {
      name: "title",
      title: "Title",
      type: "string",
    },
    {
      name: "tags",
      title: "Tags",
      type: "array",
      of: [{ type: "reference", to: [{ type: "tag" }] }],
    }
  ]
}

And another article document that looks like

{
  name: "article",
  title: "Article",
  type: "document",
  fields: [
    {
      name: "title",
      title: "Title",
      type: "string",
    },
    {
      name: "description",
      title: "Description",
      type: "text",
    },
    {
      name: "tags",
      title: "Tags",
      type: "array",
      of: [{ type: "reference", to: [{ type: "tag" }] }],
    }
  ]
}

I am unable to figure out how to get the tags with the highest reference count used across pages and articles

An extension of this question would be to get the top 10 highest tags used across the site.

I've been struggling for a while now. Any help would be appreciated.

Thank you team.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can likely accomplish this by constructing a query that first gets all tags, then uses the count function to further filter them. Something like the following:

*[_type == 'tag'] {
  ...,
  'totalReferences': count(*[_type in ['page', 'article'] && references(^._id))
} | order(totalReferences desc) [0...10]

This may not be very performant in very large datasets, though.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!