See Sanity in action 👀 Join us for a live product demo + Q&A →

Guidance on using GROQ to exclude already added documents in a sub-service array

5 replies
Last updated: Feb 17, 2023
Hey y'all, looking some some GROQ guidance,I have a type named 'service', and want to be able to list sub-services as an array of references to other 'service' documents.

When adding a new sub service ("Type to search" or going through the drop down after clicking "Add item") I want to exclude any services already added to the sub service array from the available options.

I've checked the
cheat sheet & the GROQ docs, here's what I have so far - am I even close with this?
Note I'm using a dynamic filter her as I am also using other fields to reduce the number of options - this is simply a minimal example.

export const Service = defineType({
    name: 'service',
    title: 'Service',
    type: 'document',
    fields: [
            name: 'subServices',
            title: 'Sub Services',
            type: 'array',
            of: [
                    type: 'reference',
                    to: [{ type: 'service' }],
                    options: {
                        // How do I exclude documents already added to the 'subServices' array?
                        filter: ({ document }) => {
                            return {
                                filter: '!(_id in subServices[]._ref)',
Feb 17, 2023, 11:33 AM
I’ve used something like this in the past:
filter: ({ parent }) => {
  const existingEntries = parent
    .map(existingEntry => existingEntry._ref)

  return {
    filter: `!(_id in $existingEntries) && !(_id in path('drafts.**'))`,
    params: {
Feb 17, 2023, 5:15 PM
Thank you
user M
, exactly what I needed 🙌Just curious, was my initial GROQ attempt a poor attempt at this query?
Perhaps I misinterpreted the syntax in the GROQ guides/cheatsheet?
Feb 17, 2023, 8:01 PM
No, you were basically there! This method just removes any possible null values from your existing entries and removes drafts so that you don’t see both the published and draft versions of the references.
Feb 17, 2023, 8:03 PM
Thanks for clarifying
user M
, I appreciate you taking the time to help me out with this.Have a great day
Feb 17, 2023, 8:37 PM
You too!
Feb 17, 2023, 9:07 PM – build remarkable experiences at scale

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

Categorized in