Query document by _ref number

3 replies
Last updated: Sep 13, 2023
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
The
_ref
value is equivalent to the document’s non-draft
_id
and gets ascribed to a reference, so in all cases I can think of, the answer would be yes. There’s an idiomatic approach to filtering in a subquery that uses that
_ref
value:

*[_type == 'author']{
  ...,
  'posts': *[_type == 'post' && author._ref == ^._id]
}
Here, the query for
posts
wants all posts where the author that’s referenced (from within the post document) equals the author
_id
from the top-level scope.
What you can’t really do is expect to use
_ref
at the top-level scope. E.g.,

*[_type == 'post' && _ref == $ref][0]
However, that’s because you’d use
_id
instead of
_ref
.
thanks... i went with
*[_type == 'map' && _id == '${mapID}']

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?