GROQ: Finding shared references between documents (referencedBy workaround)
This is a great share! You've discovered some really elegant GROQ patterns for finding shared references between documents, and your journey from the first working solution to the cleaner final query is a perfect example of how GROQ proficiency develops.
Your key insights are spot-on:
1. Filters accept logical expressions: You're absolutely right that the square bracket notation [condition] is a filter that can contain any boolean logic, not just array indices. This is fundamental to GROQ's power and opens up possibilities like your [one > 0 && two > 0] approach.
2. The parent reference (^) trick: Your first solution cleverly uses the parent operator ^ to reference the vendor document from within the nested query. This pattern of counting references from the "wrong direction" is a well-known GROQ workaround for the lack of a native referencedBy() function.
3. The cleaner _id in pattern: Your final query is indeed much more readable:
*[
_id in *[_id == $weddingId1].vendorList[]->_id &&
_id in *[_id == $weddingId2].vendorList[]->_id
].vendorNameThis directly expresses the intent: "find vendors whose IDs appear in both wedding vendor lists." The _id in operator combined with dereferencing (->) makes it very declarative.
Potential optimizations to consider:
If you find yourself doing this frequently or with many weddings, you could also use the count() approach inline:
*[_type == "vendor" && count(*[_id in [$weddingId1, $weddingId2] && references(^._id)]) == 2].vendorNameThis checks that exactly 2 of your specified weddings reference each vendor, which scales better if you're comparing more than two documents.
Thanks for sharing this exploration—it's exactly the kind of problem-solving that helps others learn GROQ's more advanced patterns! The progression from "it works" to "it's elegant" is where GROQ really clicks.
Show original thread10 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.