Is there a way to query documents that aren’t referenced by another type of document?

5 replies
Last updated: Nov 23, 2020

Is there a way to query documents that aren’t referenced by another type of document? I’m trying to delete documents that aren’t being referenced.

Nov 21, 2020, 11:03 PM

The closest I’ve got to working out which documents don’t have a reference is this

Nov 21, 2020, 11:04 PM

Ideally I’d want a list of

of the documents that need removing

Nov 21, 2020, 11:05 PM

Found the solution from an old script I think

user Y
had sent me to remove assets that were not being used. No idea how this query works or what it is doing but it brings me back the IDs I want to delete.

Nov 21, 2020, 11:35 PM

ah that's handy thanks, a quick explication how it works
1. fetch all documents of type offer

*[_type in ["offer"]]
2. include _id and and refs (refs containing count of references)

"refs": count(*[ references(^._id) ])
3. filter results to only show data where refs count == 0 and then return only the id

[ refs == 0 ]._id

*[ _type in ["offer"]]{
  "refs": count(*[references(^._id)])
}[refs == 0]._id

Nov 22, 2020, 9:36 AM

Thank you for taking the time to explain

user S

Nov 23, 2020, 9:21 AM Get the most out of your content is a platform to build websites and applications. It comes with great APIs that let you treat content like data. Give your team exactly what they need to edit and publish their content with the customizable Sanity Studio. Get real-time collaboration out of the box. comes with a hosted datastore for JSON documents, query languages like GROQ and GraphQL, CDNs, on-demand asset transformations, presentation agnostic rich text, plugins, and much more.

Don't compromise on developer experience. Join thousands of developers and trusted companies and power your content with Free to get started, pay-as-you-go on all plans.