How to Return Blog Posts by Slug Excluding the Slug that is being Passed to the Query
Looking at your query, you're trying to exclude a blog post by its slug. The issue is with how you're using the match operator and negation in GROQ.
The correct way to exclude posts by slug is to use the inequality operator (!=) rather than trying to negate the match operator. Here's the solution:
*[_type == 'post' && slug.current != $slug]This query will:
- Get all documents where
_typeis 'post' - AND where
slug.currentis not equal to the slug parameter you pass in
Why your queries didn't work:
*[_type == 'post' && slug.current match !$slug]- Thematchoperator is designed for text search/pattern matching, not for simple equality comparisons. You can't negate the parameter like!$slug.*[_type == 'post' && !slug.current match $slug]- While the negation syntax is closer,matchstill isn't the right operator here since you want exact exclusion, not text matching.
Additional examples:
If you want to exclude multiple slugs:
*[_type == 'post' && !(slug.current in [$slug1, $slug2, $slug3])]Or if you're working with the slug directly in your filter:
*[_type == 'post' && slug.current != 'my-specific-slug']The match operator is really meant for text search scenarios like *[title match "search*"], not for simple equality/inequality comparisons where == and != are the right tools.
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.