How to filter documents by view count field in Sanity?

1 replies
Last updated: Sep 8, 2022
Hi, how can I possibly filter a document by how many views it has as a field ?
AI Update

You can filter documents by a numeric field like views using GROQ's filter component with comparison operators. Here's how:

*[_type == "yourDocumentType" && views > 100]

This query filters documents where the views field is greater than 100. You can use standard comparison operators in GROQ filters:

  • > - greater than
  • < - less than
  • >= - greater than or equal to
  • <= - less than or equal to
  • == - equal to
  • != - not equal to

More examples:

Filter documents with at least 1000 views:

*[_type == "post" && views >= 1000]

Filter documents within a view range:

*[_type == "article" && views > 500 && views < 5000]

Get the top 10 most viewed documents:

*[_type == "post"] | order(views desc)[0...10]

You can also combine this with projections to return only specific fields:

*[_type == "post" && views > 1000]{
  title,
  views,
  publishedAt
} | order(views desc)

Important note: Make sure your views field is defined as a number type in your schema. If the field doesn't exist on some documents, you might want to add a null check:

*[_type == "post" && defined(views) && views > 100]

This ensures you're only filtering documents that actually have the views field defined. The filter component in GROQ evaluates boolean expressions for each document and returns only those where the expression is true, making it perfect for numeric comparisons like view counts.

Show original thread
1 reply
There’s nothing built into Sanity to track views, so you’d need to implement that aspect yourself. You could then store that data (either on the document, in a separate document, or outside of Sanity) and would need to factor it into your queries.

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?