How to query for document ID in Sanity GROQ?
Based on your data structure, you're looking to query products and get back the document with all its fields including the _id. Here's a GROQ query that would return that result:
*[_type == "products"]{
_id,
_createdAt,
_rev,
_type,
_updatedAt,
name,
price,
price_id,
product_id,
image
}If you want to query for a specific product (like the one in your example), you could filter by ID:
*[_type == "products" && _id == "Gk1LBo8Kg5xEVuqFLjoonz"][0]{
_id,
_createdAt,
_rev,
_type,
_updatedAt,
name,
price,
price_id,
product_id,
image
}Or if you just need the document ID as the primary result, you could simplify to:
*[_type == "products"]{
_id
}A few key points about this query:
- The
*[_type == "products"]part filters all documents to only those with type "products" - The curly braces
{}define a projection that specifies which fields to return - System fields like
_id,_createdAt,_rev, etc. need to be explicitly listed if you want them (they're not included by default in projections) - The
[0]in the second example gets just the first matching document instead of an array
If you want to expand the image asset reference to get the full image data, you could use:
*[_type == "products"]{
_id,
name,
price,
price_id,
product_id,
image{
_type,
asset->
}
}The -> operator follows the reference to get the full asset document details.
Show original thread8 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.