Query for finding un-referenced documents in Sanity.io
Yes! There's a great GROQ pattern for finding unreferenced documents. The key is to use the references() function in combination with count() to check if any documents reference each document.
Here's the basic pattern:
*[_type == "yourDocType"]{
_id,
"refs": count(*[references(^._id)])
}[refs == 0]This query:
- Fetches all documents of a specific type
- For each document, counts how many other documents reference it using
count(*[references(^._id)]) - Filters to only show documents where the reference count equals 0
The ^ operator is crucial here - it accesses the parent document's _id from within the subquery, allowing you to check "how many documents reference this document?"
If you just want the IDs of orphaned documents, you can simplify it:
*[_type == "offer"]{
_id,
"refs": count(*[references(^._id)])
}[refs == 0]._idYou can also check across multiple document types:
*[_type in ["offer", "product", "page"]]{
_id,
_type,
"refs": count(*[references(^._id)])
}[refs == 0]Performance tip: This query can be intensive on large datasets since it performs a subquery for each document. Consider running it on specific document types rather than your entire dataset, and maybe during off-peak hours if you have a lot of content.
This is particularly useful for content cleanup, identifying orphaned assets, or finding documents that might be safe to delete since nothing else depends on them. You can find more examples in the backlinks recipe which uses similar reverse reference patterns.
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.