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

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
_ids
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)

{
_id,
"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"]]{
  _id,
  "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

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?