How to filter documents by missing or unset property in GROQ?

2 replies
Last updated: Apr 16, 2020
Got a question...How do you filter by items not having a property set?
Something like
*[!prop]
doesn't seem to work, and neither does
*[prop == null]
AI Update

You're on the right track! To filter by items that don't have a property set, you need to use the defined() function in GROQ.

The correct syntax is:

*[!defined(prop)]

This will return all documents where the prop field is not defined or is null.

So if you wanted to filter posts that don't have a publishedAt property set, you'd write:

*[_type == 'post' && !defined(publishedAt)]

The defined() function returns true if the property exists and is not null, and false otherwise. By negating it with !, you get documents where the property is missing or null.

Just using *[!prop] doesn't work because GROQ needs the explicit defined() function to check for property existence. And prop == null won't catch cases where the property doesn't exist at all on the document (as opposed to existing but being set to null).

You can read more about the defined() function in the GROQ documentation.

Show original thread
2 replies
*[_type == 'post' && !defined(property)]
Nice!! Thanks a lot!

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?