👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

Filtering and grouping products based on certain values in Sanity.io

4 replies
Last updated: Jul 18, 2021
I am trying to filter products by a certain value of a field, which is not a document. Examples of a filter I want to make is whether a product is currently available (if a checkbox is selected or not) or is available in a certain week (which I save with a string like 19 July 2021 - 25 July 2021, and each product has an array of those strings), and I want to group and filter based on those values. Looking at https://www.sanity.io/docs/dynamically-group-list-items-with-a-groq-filter I only see examples to filter by documents, not a field's value, even though it's stated at the beginning of the post.
Jul 18, 2021, 4:13 PM
You can add anything into your filter that resolves to true/false. For example, let’s assume your document has a
_type
of
product
. A basic filter to return all your products would be
*[_type == "product"]
, which will consider all documents and return those where
_type == "product"
resolves to
true
. If you have a checkbox field called
available
, you could add that to your filter like this:

*[_type == "product" && available]
Which is the same as:


*[_type == "product" && available == true]
Any products returned by this query would have a
_type
of
product
and
available
checked (i.e.,
true
), which resolves to:

*[true && true]
or simply


*[true]
Products where
available
is
false
would resolve to:

*[true && false]
which is


*[false]
… and would therefore not satisfy the query.

As for availability in a certain week, that might be difficult if the date is stored as a start and end date as a string. I’d suggest storing them as
dates or datetimes (you only need to store one, as the other is just 7 days before/after), since then you can use comparison operators (
<
,
>
,
<=
,
>=
,
==
) to determine if you satisfy the query. Just like before, your comparison will resolve to a true/false value. You can pass dates into your query from your front end as parameters , which get included in the query and can return documents dynamically.
Jul 18, 2021, 5:59 PM
Thanks Geoff for the quick response! I think I had tunnel visioned on the use with child receiving something like authorId from a document and had not taken a good look at the latter part of the doc, and with your explanation this now seems really simple. Thanks!
Jul 18, 2021, 6:04 PM
Thanks Geoff for the quick response! I think I had tunnel visioned on the use with child receiving something like authorId from a document, and with your explanation this now seems really simple. Thanks!
Jul 18, 2021, 6:04 PM
You’re welcome! Have fun building!
Jul 18, 2021, 6:05 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?