How to get information from every element of an array in GROQ query?

6 replies
Last updated: Jan 22, 2022
Hi !
I got what I wanted data wise using this query, but I just got 1 element out of the array, I was wondering how to do the same but to get information from every element of the array:

Thanks in advance!
🙏
AI Update

I understand you're trying to get information from every element of an array in your GROQ query, but you're currently only getting one element. Without seeing your specific query, I can provide you with the general pattern for working with arrays in GROQ.

The key difference is between using bracket notation with an index versus using empty brackets to get all elements:

Getting a single element (what you're probably doing now):

*[_type == 'movie']{
  title,
  'firstActor': castMembers[0].person->name
}

Getting all elements from the array:

*[_type == 'movie']{
  title,
  'allActors': castMembers[].person->name
}

The [] without an index tells GROQ to iterate over every element in the array.

Here are some common patterns for working with arrays according to the GROQ query cheat sheet:

Return all items with projections:

*[_type == 'movie']{
  title,
  'cast': castMembers[]{
    characterName,
    'actorName': person->name
  }
}

Filter array elements:

*[_type == 'movie']{
  title,
  'leadActors': castMembers[featured == true]{
    characterName,
    person->name
  }
}

Get all referenced documents:

*[_type == 'book']{
  title,
  authors[]->{
    name,
    bio
  }
}

The [] operator is the key - it tells GROQ to process every element in the array rather than just selecting a single one with [0], [1], etc.

If you're getting just one element, you likely have an array index like [0] somewhere in your query. Simply remove the index and use [] instead to get all elements!

Show original thread
6 replies
Hey there! To clarify, are you not getting all of your
events
or all of your
registers
? If it's the latter, you're currently specifying
registers[0]
, which would only return the first index of the array.
This is what i’m getting. Just the first element as the query says (I did it that way cause I’m trying to get all the information, but that’s the most that I’ve got haha 😅)
If you remove the
0
, you should get all of your
registers
array back even if you are specifying a projection.
When I did this:

*[type == "event"]{
  ..., 
  registers->
}
It returned null for registers
It worked, thank you very much! 🤘
You're welcome!

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?