Filter out current document in GROQ related posts query
Perfect! You're on the right track. To exclude the current document from your related posts query, you need to filter out documents where the _id matches the parent document's _id.
Here's how to adjust your query:
"related": *[
_type == "post"
&& count(categories[@._ref in ^.^.categories[]._ref]) > 0
&& _id != ^.^._id
] | order(publishedAt desc, _createdAt desc) [0..5] {
title,
slug
}The key addition is && _id != ^.^._id. Let me break down what's happening:
^.^._iduses the parent operator to traverse up two levels to access the_idof the original document you're querying- The
@operator incategories[@._ref in ^.^.categories[]._ref]represents each item in the current document's categories array as it's being evaluated - The double
^.^is needed because you're inside a projection (the{}part) which is itself nested inside the filter
So the filter reads: "Give me posts that share categories with the parent document, but exclude the parent document itself by checking that _id doesn't match."
This is a common pattern when building "related content" features, and comparing _id values is the most reliable way to exclude the current document since _id is unique across all documents.
Show original thread2 replies
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.