Filtering documents by referenced field value in GROQ

2 replies
Last updated: Aug 16, 2022
*[_type == "post" &&  author.name == "john smith"]
, for example
AI Update

Looking at your GROQ query example, there's a small syntax issue. The query should work, but you have an extra comma before the closing bracket that's unnecessary (though GROQ is forgiving about trailing commas in some contexts).

Here's the corrected version:

*[_type == "post" && author.name == "john smith"]

Let me break down what this GROQ query does:

  • * - Returns all documents you have permission to read
  • [...] - The filter that keeps only documents where the condition is true
  • _type == "post" - Matches documents with type "post"
  • && - Logical AND operator
  • author.name == "john smith" - Matches where the author's name field equals "john smith"

Important consideration: This query assumes author is an object directly on the post document with a name field. If author is actually a reference to another document (which is common in Sanity schemas), you'll need to use the reference operator (->) to dereference it:

*[_type == "post" && author->name == "john smith"]

The -> operator resolves the reference and lets you access fields from the referenced author document.

If you want to return specific fields rather than the entire document, add a projection:

*[_type == "post" && author->name == "john smith"]{
  title,
  publishedAt,
  "authorName": author->name
}

You can test your queries using the Vision plugin in your Sanity Studio to see the results in real-time!

Show original thread
2 replies
If you're trying to match an array of categories to another array of categories, you'll need to use this method!

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?