Querying for a specific item type within a document in Sanity.io

16 replies
Last updated: Aug 15, 2021
Or better yet how can I query ALL items of _type ?
AI Update

To query all documents of a specific type in GROQ, you can use a simple filter pattern. Here's the basic syntax:

*[_type == "yourTypeName"]

The * returns all documents, and the filter [_type == "yourTypeName"] keeps only documents where the _type field matches your specified type.

For example, to get all blog posts:

*[_type == "post"]

To get all authors:

*[_type == "author"]

You can also add projections to shape the returned data:

*[_type == "post"]{
  _id,
  title,
  publishedAt,
  author->
}

This follows the fundamental GROQ query pattern of *[<filter>]{<projection>}, where:

  • * fetches all documents you have permission to read
  • The filter [] keeps only matching documents
  • The projection {} shapes what fields are returned

If you want to retrieve all documents regardless of type, you can simply use:

*

Or with a projection to see their types:

*{_type, _id, title}

You can test these queries using the Vision plugin in your Sanity Studio, which provides a visual interface for experimenting with GROQ queries and seeing results in real-time.

*[_type == "limitedImage*"]*
*[_type == "image*"]*
*[_type == "whateveryourtypeis*"]*
This is not working as limitedImage is not a document but an item inside
an item inside what?
I’m not sure I understand your issue 🤔
An item inside document
The type I'm trying to batch edit is an item inside a document, not a document itself
ah, well I guess you want to get every document and test if the type exists inside of it?
Yeah anywhere in the document,
I couldn't find a query for this
Or documentation
do you know the field the _type is used on?
*[]
gets every document and returns every field from each of those documents
you could then loop over that response, traversing every field until you find your type
It varies how deep it is, there's no consistence
Ok, so this a script I used to update all the values of a
link
object (there was an issue with a content migration where where we needed to find all instances of
url
and changed it to be
href
)
This might be a good starting point for you?

/**
 * Use to check for link 'url' properties that have been migrated incorrectly.
 * Run this script with: `sanity exec --with-user-token scripts/migrate/patchLink.ts`
 */

 import sanityClient from 'part:@sanity/base/client';
 import consola from 'consola';
 
 const client = sanityClient.withConfig({
   dataset: 'dev',
   apiVersion: 'v2020-03-15',
 });
 
 const patchDocument = (obj, updateDocument) => {
   if (obj !== null) {
     Object.entries(obj).forEach(([key, value]) => {
       // find the _type you're looking for
       if (key === '_type' && value === 'link') {
         // do what you need to to the data of that object 
         if (obj.url) {
           if (!obj.href) {
             obj.href = obj.url;
           }

           delete obj.url;

           updateDocument = true;
         }
       } else if (typeof value === 'object') {
         updateDocument = patchDocument(value, updateDocument);
       }
     });
   }
 
   return updateDocument;
 };
 
 const runProcess = async () => {
   const allDocuments = await client.fetch(`*[]`);
 
   let documentsUpdated = 0;
   const concurrency = 50; // keep under sanity rate limit
 
   console.time('patchLink');
 
   while (allDocuments.length) {
     await Promise.all(
       allDocuments.splice(0, concurrency).map(async doc => {
         const updateDocument = patchDocument(doc, false);
 
         if (updateDocument) {
           const docTitle =
             (doc._type == 'profile' && `${doc.firstName} ${doc.lastName}`) || doc.title?.en_GB || doc.title || doc._id;
           consola.success(`Fixing (${doc._type}) ${docTitle}`);
 
           await client.createOrReplace(doc);
 
           documentsUpdated++;
         }
       })
     );
   }
 
   <http://consola.info|consola.info>(`Number of documents updated: ${documentsUpdated}`);
   console.timeEnd('patchLink');
 };
 
 runProcess();
 
That code could probably be much nicer, but it did the trick.. though it is slow (took ~5mins to run) as it had to dive through so many documents and levels
Thanks I'll give it a check soon!

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?