Calculating total documents in Sanity usage using GROQ queries

2 replies
Last updated: Jun 4, 2024
Hey hey!
Can I ask how “total documents” is calculated in Sanity usage?
I’m asking because I’m trying to replicate that number using a GROQ query, to keep track of our documents.

I end up with either too many, or too few, depending on how I’m counting.
For example, do total documents count across datasets?
AI Update

Great question! The "total documents" number in Sanity usage is calculated with some specific rules that might explain why your GROQ query results differ.

What's Counted in Total Documents

According to the Plans and Payments documentation, the Documents quota is defined as:

"total number of stored documents (including drafts) across all datasets at the end of the month"

Important exclusions:

  • System documents are NOT counted toward your quota (things like sanity.imageAsset, configuration documents, etc.)
  • Assets are NOT counted as documents toward your quota
  • Drafts ARE counted (they're included in the total)

Replicating the Count with GROQ

Based on the community discussion, here's how to replicate the usage count:

count(*[_type in $types])

Where $types is an array of the document types you've defined in your schema (excluding system documents and assets).

If you're getting too many documents, you're likely including:

  • System documents (those with _id starting with _)
  • Asset documents (sanity.imageAsset, sanity.fileAsset)

If you're getting too few, you might be:

  • Missing some custom document types from your types array
  • Not including drafts (draft documents have _id starting with drafts.)

Dataset Considerations

Yes, documents count across ALL datasets in your project. The quota is per-project, not per-dataset. So if you have multiple datasets (like production, staging, development), all their documents add up to your total count.

Practical GROQ Query

To get an accurate count excluding system documents and assets:

count(*[!(_id in path("_.**")) && !(_type match "sanity.*")])

This excludes:

  • System documents (those in the _ path)
  • Sanity's internal types (like sanity.imageAsset)

Remember that this count includes drafts, which is consistent with how Sanity calculates your usage quota.

count(*[])
would count all documents in a dataset. This, however, would count all system documents and assets. Those aren’t counted toward your quota. I think something along the lines of
count(*[_type in $types])
where
$types
is an array of the document types you’ve defined in your schema should do it.
Thank you!

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?