Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Fetching random documents using queries in Sanity.io

4 replies
Last updated: Aug 22, 2024
Hi all! anyone with tips for how to get random documents in a query? or a work around for it? I guess I could write in random numbers in a field on a cron job or something, but would be nice to see if its any better approaches. Seems its not directly supported in the API.
Aug 22, 2024, 12:55 PM
In two queries you could do it like this:

const total = await client.fetch("count(*)")

const randomIndex = Math.floor(Math.random() * (total + 1))

const random = await client.fetch("*[$randomIndex]", {randomIndex})
Aug 22, 2024, 1:28 PM
Ok, thanks. That code is a bit new for me, if its random by some specific types for instance “doc”, would it be like this then?

const total = await client.fetch("count(*[_type == 'doc')")

const randomIndex = Math.floor(Math.random() * (total + 1))

const random = await client.fetch("*[$randomIndex]", {randomIndex})
Aug 22, 2024, 2:02 PM
Close:

const total = await client.fetch("count(*[_type == 'doc'])")

const randomIndex = Math.floor(Math.random() * (total + 1))

const random = await client.fetch("*[_type == 'doc'][$randomIndex]", {randomIndex})

Aug 22, 2024, 2:12 PM
thanks a lot:)
Aug 22, 2024, 2:23 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?