Go Behind the Experience to see how Tecovas brings the West to life with Sanity 🤠 July 18th

Filtering duplicate references in multiple documents in Sanity.io

6 replies
Last updated: Jun 7, 2022
Hi everyone,
Could anyone please help with this problem: so we are trying to filter out any duplicate references on ALL posts/documents (of the same type).

I have seen this example below but this is for an individual document and works perfectly.

filter: ({ parent }) => {
   const existingEntries = parent.map(existingEntry => existingEntry._ref).filter(Boolean)
   return {
     filter: '!(_id in $existingEntries)',
     params: {
I am also aware of this approach but still can’t get my head around GROQ logic to filter multiple references against multiple documents (of the same type).

filter: ({ document }) => ({
          filter: '$id in castMembers[].person._ref',
          params: {
            id: document.actor._ref,
As you can see by the
attached image it’s an array of references.
Thanks in advance, any advice would be appreciated.
Jun 6, 2022, 10:34 AM
user Q
! To check I'm understanding correctly, you want to create a filter that prevents a document from being referenced in the Creator Projects array in more than one document that contains a Creator Projects array?
Jun 6, 2022, 4:56 PM
Hi! yes, that's correct. I've attached screenshots that might make things clearer. Thanks
Jun 6, 2022, 6:18 PM
Got it! You'll need to use an async function & import the client to fetch all of the documents that are already referenced. For example:
      name: 'filteredRef',
      title: 'Filtered Ref',
      type: 'array',
      of: [
          type: 'reference',
          to: [{ type: 'movie' }],
          options: {
            filter: async ({ document }) => {
              const existingRefs = await client
                  `*[_type == $documentType && defined(filteredRef)].filteredRef[]._ref`,
                  { documentType: document._type }
                .then(refs => refs.filter(Boolean));
              return {
                filter: '!(_id in $existingRefs)',
                params: { existingRefs },
Jun 6, 2022, 6:59 PM
Ah cheers, I will give this a whirl.
Jun 6, 2022, 7:29 PM
That worked a charm. Thanks again 🥲
Jun 7, 2022, 12:36 PM
So glad it worked for you!
Jun 7, 2022, 4:42 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?