Sekrab Garage

Sanity.IO GROQ Count

Get results and total count of Sanity records by GROQ

TipHosting February 26, 22
Subscribe to Sekrab Parts newsletter.

To retrieve the results and the total, using GROQ for Sanity.IO, you need to start by projecting your own model like this:

query = `{
    "items": *[_type == "post"] | order(publishedAt desc)[1...5],
    "total": count(*[_type == "post"]) 

}`

The result looks like this

{
    "ms": 65,
    "query": "...",
    "result": {
        "items": [
            {...}
        ],
        "total": 34
    }
}

It looks obvious, but I had to read How Queries Work all the way to the end to figure out I can project my own outer model. Hope this helps someone.