Is there a way to write a groq query that checks if a boolean is true, and if so, returns an array of referenced documents? (example use case, on a homepage, I want to allow...
You can use the select() function in GROQ to conditionally return an array based on a boolean value. The select() function works like a switch statement and evaluates conditions in order, returning the first matching value.
For your use case of showing/hiding the 3 most recent blog posts based on a boolean, here's how to structure it:
*[_id == "homepage"][0] {
...,
"posts": select(
showBlogPosts == true => *[_type == 'post'] | order(publishedAt desc) [0..2] {
title,
slug,
publishedAt
},
[]
)
}This query:
- Checks if
showBlogPostsistrue - If true, returns an array of the 3 most recent posts
- If false (or undefined), returns an empty array
[]
You can also use a more concise version if your boolean field might be undefined:
*[_id == "homepage"][0] {
...,
"posts": select(
defined(showBlogPosts) && showBlogPosts => *[_type == 'post'] | order(publishedAt desc) [0..2] { ... },
[]
)
}The key differences from your original attempt:
- Use the
select()function with a condition-value pair syntax:condition => value - The condition checks your boolean field directly
- Provide a fallback value (empty array) when the condition is false
- The entire subquery goes after the
=>arrow
You can also use this pattern within projections if you have multiple features to toggle:
*[_id == "homepage"][0] {
title,
"blogSection": select(showBlogPosts => {
"posts": *[_type == 'post'] | order(publishedAt desc) [0..2] { ... }
}),
"newsSection": select(showNews => {
"items": *[_type == 'news'] | order(_createdAt desc) [0..5] { ... }
})
}This gives your clients flexible control over which content sections appear on the homepage!
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.