Can you write a conditional GROQ request based on document fields in Sanity.io?

6 replies
Last updated: Feb 27, 2023
Is it possible to write a conditional groq request based on document fields? E.g. if I want to query for a specific field only if a filter is set (the filter is set in another document reference, so it can't be done with JS).
To give a little more context, here's a code example with just one filter. This works, but it becomes a total mess if I add more filters and they are going to be combined.

"models": select(
  type == "brand" => select(
    filterVehicleGroup != null => *[_type == "model" && brand._ref == ^.brand._ref && vehicleGroup == ^.filterVehicleGroup] | order(_createdAt desc) {
      "_key": _id,
      ${MODEL_CONTENT}
    },
    *[_type == "model" && brand._ref == ^.brand._ref] | order(_createdAt desc) {
      "_key": _id,
      ${MODEL_CONTENT}
    },
  ),
  type == "selected" => selected[]-> {
    _key,
    ${MODEL_CONTENT}
  }
)
Where in this query are you trying to add the additional filter?
This is just an example where
filterVehicleGroup
is the filter. The idea is to add multiple filters in the same way, where it adds it to the query if it's set or not equal to "all", like this for each filter:

filterFieldNameInDoc == filterValue
user M
I see that you have liked my message, and it's for sure a lot of messages to follow up on, but is it possible to add filters like this in GROQ without using select to check if there is null to exclude the filtering?
Did some more research and found a solution. Will paste it below if anyone else has a similar question 😊

*[_type == "model"
  && ($filter1 == null || filter1 == $filter1) 
  && ($filter2 == null || filter2 == $filter2) 
  && ($filter3 == null || filter3 == $filter3) 
  && ($filter4 == null || filter4 == $filter4) 
  && ($filter5 == null || filter5 == $filter5)
]
Thanks for sharing your solution!

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?