Querying objects with specific references in a Slack thread.

2 replies
Last updated: Jul 13, 2023
HI All, I'm sure I'm missing something obvious but I can't for the life of me get this simple query working. I have a a load of objects with an array of references that look something like this:
{
  "_id": "9525c913-2016-47f5-b954-c71bad6b69e1",
  "_type": "article",
  "relatesTo": [
    {
      "_key": "d24ea1901b95",
      "_ref": "113d6739-9582-4160-9008-324d856c4f3b",
      "_type": "reference"
    },
    {
      "_key": "9803a859f8dd",
      "_ref": "4ada924e-8bae-4479-96a8-4a4d0eddf81b",
      "_type": "reference"
    }
  ]
  "title": "My Object"
  ... more fields here
}
I'm trying to work out a query to pull back the specific objects (let's say I want to project
_id
and
title
) where the
relatesTo
field contains a
_ref
with a specific value. I don't think I need to dereference the reference objects.
I don't want to use
references()
because I want to make sure the reference comes from the specific
relatesTo
field. I've tied numerous permutations, but can't get it to work. Any help greatly appreciated!
Jul 13, 2023, 2:22 PM
Hi
user S
. You’re right that if you know the
_ref
, you won’t need to dereference to do the comparison. By using the
in
operator, you can look for a string value in an array of strings. I might do something like this to get my results, and then use a projection from there:

*[_type == 'article' && '113d6739-9582-4160-9008-324d856c4f3b' in relatesTo[]._ref]
Jul 13, 2023, 2:49 PM
You beauty! Thanks Geoff!
Jul 13, 2023, 2:51 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?