How to filter documents by view count field in Sanity?
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 thread1 reply
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.