How to Return Blog Posts by Slug Excluding the Slug that is being Passed to the Query

2 replies
Last updated: Aug 3, 2021
Hi everyone, it's me again. πŸ˜›
I trying to return blog posts by slug excluding the slug that is being passed to the query.

I've tried the following without success:


*[_type == 'post' && slug.current match !$slug]
*[_type == 'post' && !slug.current match $slug]

AI Update

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 _type is 'post'
  • AND where slug.current is not equal to the slug parameter you pass in

Why your queries didn't work:

  1. *[_type == 'post' && slug.current match !$slug] - The match operator is designed for text search/pattern matching, not for simple equality comparisons. You can't negate the parameter like !$slug.

  2. *[_type == 'post' && !slug.current match $slug] - While the negation syntax is closer, match still 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.

Have you tried
*[_type == 'post' && !(slug.current match $slug)]
user A
Thank you, that worked. 😎 πŸŽ‰

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?