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

How to retrieve specific values from a document reference in GROQ query.

5 replies
Last updated: Aug 1, 2023
Hello DevI only want to get "NextJS" of the title from the reference of the tag in the document of "gorq", how do you guys solve it?

export default defineType({
  name: 'contents',
  title: 'Contents',
  type: 'document',
  fields: [
    defineField({
      name: 'tags',
      title: 'Tags',
      type: 'array',
      of: [{type: 'reference', to: [{type: 'tags'}]}],
    }),
  ],
})

*[_type == "contents" && tags[]-> title == "NextJS" ] {
...
}
Jul 31, 2023, 3:20 PM
The GROQ looks correct. What issue are you facing and what are the actual and expected results? If you are looking to retrieve only specific values from the result, you can use projections , something like this:
*[_type == "contents" && tags[]->title == "NextJS"] {
 _id,
 title,
 "Titles": tags[]->title,
}
Jul 31, 2023, 3:29 PM
user F

*[_type == "contents" ] {
 tags[]->{
   title
 }
}

**result**
  0:{…} 1 property
  tags:null
  1:{…} 1 property
    tags:[…] 2 items
      0:{…} 1 property
    title:flutter
      1:{…} 1 property
    title:NextJS
  2:{…} 1 property
    tags:null
  3:{…} 1 property
    tags:[…] 2 items
      0:{…} 1 property
        title:zustand
      1:{…} 1 property
        title:NextJS
  4:{…} 1 property
    tags:null
  5:{…} 1 property
    tags:null
Jul 31, 2023, 5:11 PM
If you do this, you'll get it, but if you use the one
user F
did, you won't get it
Jul 31, 2023, 5:12 PM
Try this maybe?
*[_type == "contents" && tags[]->title match "NextJS"] {
 "Titles": tags[]->title,
}
Aug 1, 2023, 8:38 AM
Thanks to you, I solved it! Thank you
user F
Aug 1, 2023, 10:09 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?