How to exclude the current person from a query in Sanity.io

2 replies
Last updated: Aug 15, 2023
How do I exclude current 'item' from a query? Need to query all persons except the current person.


export const teamMemberQuery = groq`*[_type == "person" &&  slug.current == $slug][0]{ 
    name,
    _id,
    _ref,
    slug,
    "functionTitle": functionTitle[_key == $language][0].value,
    "bio" : bio[_key == $language][0].value,
    "usps": usps[_key == $language][0].value,
    "tags": tags[_key == $language][0].value,
    image {
					asset->{
						...,
						metadata
					}
				}, 
    "relatedPersons": *[_type == "person" && (person._id != _id) && defined($language)] | order(publishedAt desc) {
      name,
    },
AI Update

Looking at your query, I can see the issue. In your nested relatedPersons query, you're trying to reference the parent document's _id with person._id != _id, but this won't work as expected because you need to use the parent operator (^) to access the outer scope.

Here's the corrected query:

export const teamMemberQuery = groq`*[_type == "person" && slug.current == $slug][0]{ 
    name,
    _id,
    _ref,
    slug,
    "functionTitle": functionTitle[_key == $language][0].value,
    "bio" : bio[_key == $language][0].value,
    "usps": usps[_key == $language][0].value,
    "tags": tags[_key == $language][0].value,
    image {
        asset->{
            ...,
            metadata
        }
    }, 
    "relatedPersons": *[_type == "person" && _id != ^._id && defined($language)] | order(publishedAt desc) {
      name,
    },
}`

The key change is _id != ^._id instead of person._id != _id. The ^ operator accesses the parent scope (the current person document), so ^._id refers to the _id of the person you're querying, and _id refers to each person being evaluated in the nested query.

Also note that I removed person._id since you're already filtering on person documents directly - you just need _id to reference each candidate document's ID in the nested query.

The parent operator is specifically designed for cases like yours where you need to reference values from the outer document while filtering in a nested query. It's particularly useful when creating nested queries where inner queries need to reference values from outer documents.

*[_type == "person" && ^._id != _id && defined($language)]

user A
that was quick. Thank you πŸ‘

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.

Was this answer helpful?