How to query images by tag in sanity-plugin-media using GROQ?

6 replies
Last updated: Dec 1, 2025
Hello, Nice to be here. I have a question about Media Browser. specifically about https://www.sanity.io/plugins/sanity-plugin-media .I have some tags and images attached to tags. I wonder is there a way to get all the images of a tag? name and url using GROQ?
AI Update

Welcome to the Sanity community! Yes, you can query images by tag using GROQ with the sanity-plugin-media plugin.

According to the official documentation, tags are stored as weak references in the opt.media.tags field on asset documents. The plugin defines a media.tag document type for the tags themselves. Here's how to query images by tag:

To get all images with their associated tags:

*[_type == 'sanity.imageAsset'] {
  originalFilename,
  url,
  "tags": opt.media.tags[]->name.current
}

To filter images by a specific tag name:

*[_type == 'sanity.imageAsset' && references(*[_type == 'media.tag' && name.current == 'your-tag-name']._id)] {
  originalFilename,
  url,
  "tags": opt.media.tags[]->name.current
}

To get all images that have at least one tag:

*[_type == 'sanity.imageAsset' && count(opt.media.tags) > 0] {
  originalFilename,
  url,
  "tags": opt.media.tags[]->name.current
}

Important notes about the schema structure:

  • Tags are stored in the opt.media.tags array on each asset document (as weak references to media.tag documents)
  • Tag names use the name.current property because they're defined as slugs
  • The opt.media namespace is used because this is a third-party plugin
  • You use the -> operator to dereference the weak references and access tag properties

You can also query additional asset fields alongside tags:

*[_type == 'sanity.imageAsset'] {
  originalFilename,
  url,
  altText,
  description,
  title,
  "tags": opt.media.tags[]->name.current
}

The official documentation confirms this approach in their FAQ section, where they provide an example query showing how tags are accessed via opt.media.tags[]->name.current.

You can test these queries in the Vision plugin (usually at http://localhost:3333/vision in your local studio) to explore your data structure and refine your queries based on your specific needs.

Show original thread
6 replies

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?