I'm new using Sanity and I'm trying to filter my sanity studio posts by category, I've been looking for answers and trying different queries, but this is the only one that has worked `
*[_type == "post"
&& defined(slug.current)
&& (!defined($search) || title match $search || publishedAt match $search || author->name match $search)
&& defined($category)
&& select(defined($category) => $category in categories[]->slug.current,true) ]
| order(publishAt desc){
title,
publishedAt,
"categories": coalesce(
categories[]->{
_id,
slug,
title
},[]
),
author->{
name,
}
}`:
It works for one category but I want to filter by an array of categories.
I could find the solution:
*[
_type == "post" &&
count((categories[]->slug.current)[@ in $category]) > 0
]
Selects all documents of type "post".
Checks if any of the referenced categories have a slug that matches any category passed as parameter.
Returns posts that have at least one matching category.
`categories[]` - This accesses the array of categories in your document. The `[]` indicates you're working with all elements in the array.
`categories[]->` - The arrow operator (`->`) resolves references. This means your categories are stored as references to other documents, not as direct values.
`categories[]->slug.current` - After resolving the references, this accesses the `slug.current` property of each referenced category document.
`(categories[]->slug.current)[@ in $category]` - This is a filter operation on the array of slug values:
`count(...)` - This function counts how many items remain in the array after filtering
So, the entire expression counts how many of your post's categories have slugs that match the array passed as parameter. If the count is greater than 0, it means the post has at least one of those categories.
This filtering technique is documented in the [Query Cheat Sheet](<https://www.sanity.io/docs/content-lake/query-cheat-sheet>), which shows examples of filtering documents based on referenced categories.