Sanity.io GROQ: retrieve documents that have a key defined inside array of objects

1.1k Views Asked by At

I have documents that look like this

{
  "_type": "celeb",
  "name": "foo",
  "facts: [
    {a: 1, topics: {_ref: 'asd', _type: 'reference'}},
    {a: 2},
    {a: 3, topics: {_ref: 'dfg', _type: 'reference'}}
  ]
}

Not all documents have facts that have topics. Some have facts that don't have topics. I'm trying to retrieve the ones that have it. I tried the following GROQ query

*[_type == 'celeb' && defined(facts[*].topics)]

The problem with the query above is that it doesn't discriminate between celebs that have facts which have objects containing topics key, and celeb that have facts which do not have any objects containing topics key.

How can I make the query return only celeb documents that have facts which have objects that have topics defined?

1

There are 1 best solutions below

7
On

defined(foo) is just shorthand for foo != null, so that won't work. The solution is to count:

*[_type == 'celeb' && count(facts[].topics) > 0]