Query document by _ref number

3 replies
Last updated: Nov 29, 2025
is it possible to query for a document based on its
_ref
number?
AI Update

Yes, you can definitely query for a document based on its _ref value! The _ref is essentially the document ID that a reference field points to, so you can use it to find documents.

Here are the main approaches:

Direct Query by _id

Since a _ref value is just the _id of the referenced document, you can query directly for that document:

*[_id == "your-ref-value"][0]

This will return the document that has that specific ID.

Find Documents That Reference a Specific Document

If you want to find all documents that contain a reference to a specific document, use the references() function:

*[references("document-id")]

This searches for any document that has a reference field pointing to the specified ID.

Query Within Specific Reference Fields

You can also query for documents based on a specific reference field:

*[_type == "employee" && department._ref == "engineering"]

This finds all employee documents where the department reference field points to the document with ID "engineering".

Following References

Once you have a reference, you can use the reference access operator (->) to resolve it and get the full referenced document:

*[_type == "employee"]{
  name,
  department->
}

The key thing to remember is that _ref values are just document IDs, so you can use them anywhere you'd use an _id in your GROQ queries. The bidirectional nature of references in Sanity means you can query from either direction - from the referencing document to the referenced one, or vice versa.

Show original thread
3 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.

Was this answer helpful?