GROQ: Query products through shopifyProduct variants to find references
When working with nested references in a Shopify + Sanity schema, the key is using GROQ's in operator combined with the reference access operator (->) to traverse through multiple levels of references.
Based on your schema structure where:
productdocuments have astoreobject (or similar)- That object contains a
variantsarray with references toproductVariantdocuments - Each
productVarianthas an array field (likeattributes) containing references to your custom attribute documents
The solution is to use the in operator to check if a specific value exists anywhere in the dereferenced chain:
*[_type == 'product' && 'your-attribute-id' in store.variants[]->attributes[]->_id]Or if you're looking for a specific field value within the attribute:
*[_type == 'product' && 'apparel_color' in store.variants[]->attributes[].attribute->key]How this works:
store.variants[]->dereferences all variant references in the arrayattributes[]accesses the attributes array in each dereferenced variant.attribute->(if attributes contain references) or just->dereferences each attribute reference- Finally, access the field you want to match against (like
key,_id, etc.) - The
inoperator checks if your target value exists anywhere in the resulting flattened array
GROQ automatically flattens nested arrays when you chain array accessors ([]), which makes this pattern work elegantly for deeply nested references.
You can learn more about the references() function and the reference access operator (->) in the GROQ documentation. While references() is great for direct references, the in operator with dereferencing is more flexible for these nested relationship queries.
Show original thread9 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.