How to maintain order when joining data from documents in an array of document references in Sanity.io

15 replies
Last updated: Feb 7, 2023
Hi everyone, I’m running into an issue when joining data from documents in an array of document references . I’ve got an home page that has a couple of services and I need to get the title, description and an image from them.When I join the data the order of them changes. I’ve tried to order by priority, updatedAt etc. but I can’t get it to match. Currently I’m storing the order in order array and the match it on the client side but it’s very annoying and can’t be the way to go.

Order in reference array:

Service A, Service B, Service C

Order when joining the data:

Service B, Service C, Service A

Current query:

*[_id == "home-page"][0] {
  "_page_id": _id,
  _updatedAt,
  title,
  hero_image,
  "services_order": services,
  "services": *[_id in ^.services[]._ref] {
    _id,
    title,
    summary,
    poster,
  },
}
Does anyone know how to get the order to stay the same? I’m in V2 if that helps.
AI Update

The issue you're experiencing is a common gotcha with GROQ queries! When you use *[_id in ^.services[]._ref], you're creating a new query that fetches all matching documents, but GROQ doesn't automatically preserve the original array order - it returns them in whatever order the Content Lake provides them.

The good news is there's a much better solution than maintaining a separate order array on the client side. You should dereference the array directly using the -> operator instead of doing a separate query. This preserves the original order:

*[_id == "home-page"][0] {
  "_page_id": _id,
  _updatedAt,
  title,
  hero_image,
  "services": services[]-> {
    _id,
    title,
    summary,
    poster,
  },
}

The key change is services[]-> instead of your separate *[_id in ^.services[]._ref] query. The reference access operator (->) dereferences each item in the array while maintaining the original order.

Here's what's happening:

  • services[] iterates through your array of references in order
  • -> dereferences each reference to get the full document
  • The projection { _id, title, summary, poster } selects only the fields you need

This approach works because you're not creating a separate query that searches for matching documents - you're directly following the references in the order they appear in your array. The -> operator internally performs the lookup for each reference while preserving array position.

This is the standard pattern for working with arrays of references in GROQ and will give you Service A, Service B, Service C in exactly the order you have them stored in your services array. No more client-side matching needed!

One approach to simplify the task would be to utilize a field type array. You can flexibly reference and drag-and-drop these document types, to rearrange their order.
This
Guide is a great example of how it's done. In the example it shows how you can set this up with objects. The same can be done with referenced documents
You would then just call your documents like this
services-> {
  _id,
  title,
  summary,
  poster,
}
By doing that do I have to create the services on the home page? Don’t want that as I want to have one source of truth. So I’d like to get the data from the service docs I’ve already created.
This is the code I’ve got at the moment:

{
  name: "services",
  type: "array",
  title: "Services",
  fieldset: "services",
  of: [
    {
      type: "reference",
      to: [{ type: "service" }],
    },
  ],
}
I did find this document, sort-order . It could be a possible solution
Otherwise I also recommend using an
order function on your GROQ query. Hopefully these two options will work out well for you
So my issue is not with Sanity but with the GROQ queries. The examples found on the page you sent don’t work for me. I might have missed some queries or the way I join is not the optimal way, not sure. The only thing I know is that it’s weird how I can’t join the in the order I’ve sorted them by in Sanity
Sorry if I'm not understanding right. I did mention another link where it uses the order function , for the query, you could use it like this
"services": *[_id in ^.services[]._ref] | order("services_order"){
  _id,
  title,
  summary,
  poster,
},
I just tried it on vision and I see what you mean when it goes out of order when you query. I was able to get it back to the order I want by using
order()
Yeah I've tried to order function but it still doesn't work for me. I've attached some screen shots that might explain it a bit more. I tried you
order("services_order")
but it doesn't work either. I assume it's because I just create it in the same query. I did also try to order by
^.services
but that didn't work either.
The original query and in the result you can see how the ids aren't in the same order.
services_order
has the correct order from Sanity.
Not sure if it's just a matter of finding the correct `order()`query.
Hey everyone, since I haven't found a working solution for this issue, I thought I'd post it again. Please refer to the screen shots in the last post. I'm trying to get my join ("services") to keep the order that you see in "services_order". Any suggestions on how I can approach this?
user J
Are you able to help me with this one?
Hello
user B
you should look into ordering with groq
and you can also reference the services directly:

"services_order": services->{_id, title, poster}

After a lot of looking around the solution was
"services": services[]->{_id, title, poster}
the proper order is kept
without the square brackets it won’t work. Swear I tried it earlier and it didn’t work, but might have had a space in there somewhere
Oh yes sorry of course you need the brackets! I typed that up on my phone and forgot, sorry 🙂

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?