Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Content Collections and Markdown

Querying Content Collections

Query Astro content collections with getCollection, getEntry and getEntries. Filter drafts, sort by date, group by tag and build pages from entries.

Once a collection is defined, you read it from your pages with a few helper functions imported from astro:content. They run in the component script, at build time for static pages, so the data is already in the HTML when a visitor arrives. This lesson covers the three query functions, common patterns (filtering, sorting, grouping) and how to turn entries into pages.

getCollection

getCollection("name") returns all entries of a collection as an array. Each entry looks like this:

TypeScript
{
  id: "first-post",        // from the file path or the loader
  data: { title: "...", pubDate: Date, tags: [...] },   // validated by the schema
  body: "raw markdown text",                            // for Markdown-like entries
  filePath: "src/content/blog/first-post.md",
  rendered: { html: "..." }                              // when pre-rendered
}

A simple blog index:

ASTRO
---
import { getCollection } from "astro:content";
import BaseLayout from "../../layouts/BaseLayout.astro";

const posts = await getCollection("blog");
---
<BaseLayout title="Blog">
  <ul>
    {posts.map((post) => (
      <li><a href={`/blog/${post.id}`}>{post.data.title}</a></li>
    ))}
  </ul>
</BaseLayout>

All the content lives under post.data, and the shape is typed from your schema, so your editor completes post.data.pubDate and reports an error for post.data.pubdate.

Filtering

getCollection takes an optional filter function as a second argument. Only entries that return true are included. The usual use is hiding drafts in production:

ASTRO
---
const posts = await getCollection("blog", ({ data }) => {
  return import.meta.env.PROD ? data.draft !== true : true;
});
---

import.meta.env.PROD is true in a production build, so drafts appear in development and disappear when you deploy. Filtering inside getCollection is better than filtering afterwards because the loader can skip work for entries you do not need.

Sorting

Collections come back in no guaranteed order, so sort explicitly. Sort by date newest first:

ASTRO
---
const posts = (await getCollection("blog")).sort(
  (a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf(),
);
const [latest, ...older] = posts;
---

Because pubDate was defined with z.coerce.date(), it is a real Date, so subtraction of valueOf() is safe.

Three query functions

getCollection All entries, optional filter
getEntry One entry by id
1 / 2

getEntry and getEntries

getEntry fetches one entry by collection name and id. It returns undefined if the id does not exist, so handle that case:

ASTRO
---
import { getEntry } from "astro:content";

const post = await getEntry("blog", "first-post");
if (!post) {
  return Astro.redirect("/404");
}
---
<h1>{post.data.title}</h1>

getEntries fetches several entries at once, mainly from references, a schema feature that links collections together:

TypeScript
import { defineCollection, reference, z } from "astro:content";

const blog = defineCollection({
  loader: glob({ pattern: "**/*.md", base: "./src/content/blog" }),
  schema: z.object({
    title: z.string(),
    author: reference("authors"),                 // one author id
    related: z.array(reference("blog")).default([]), // list of post ids
  }),
});
ASTRO
---
import { getEntry, getEntries } from "astro:content";

const post = await getEntry("blog", "first-post");
const author = await getEntry(post.data.author);        // resolves the reference
const related = await getEntries(post.data.related);    // resolves many
---
<p>By {author.data.name}</p>
<ul>{related.map((r) => <li>{r.data.title}</li>)}</ul>

If a referenced id does not exist, the build fails, so broken links between content are caught early.

Grouping and counting

Group posts by tag to create a tag index. This is plain JavaScript on the array:

ASTRO
---
const posts = await getCollection("blog");
const byTag = new Map<string, typeof posts>();
for (const post of posts) {
  for (const tag of post.data.tags) {
    byTag.set(tag, [...(byTag.get(tag) ?? []), post]);
  }
}
const tags = [...byTag.keys()].sort();
---
<ul>
  {tags.map((tag) => (
    <li><a href={`/tags/${tag}`}>{tag}</a> ({byTag.get(tag)!.length})</li>
  ))}
</ul>

Pages from entries

Combine the query with a dynamic route from Dynamic routes. Each entry becomes a page and its body is rendered with render(), which is the topic of the next lesson, Rendering entries:

ASTRO
---
// src/pages/blog/[id].astro
import { getCollection, render } from "astro:content";

export async function getStaticPaths() {
  const posts = await getCollection("blog", ({ data }) => !data.draft);
  return posts.map((post) => ({ params: { id: post.id }, props: { post } }));
}

const { post } = Astro.props;
const { Content } = await render(post);
---
<h1>{post.data.title}</h1>
<Content />

Stand-in: query functions over an array

The following stand-in implements getCollection (with filter), getEntry and getEntries over an in-memory store, and then runs the sort and group patterns from this lesson.

Node.js Stand-in: getCollection, getEntry, getEntries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Stand-in: building pages from entries

This stand-in imitates getStaticPaths plus render() and writes a map of output files, including a tag listing, so you can see how entries turn into a site.

Node.js Stand-in: entries to static pages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Performance notes

  • Call getCollection once per page and reuse the result; avoid calling it inside a loop.
  • For huge collections, filter early and render only what the page needs.
  • The data store is cached between builds, so repeated builds only re-process changed files.
  • Entries from getCollection are plain objects, so you can use any array method.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does getEntry return for an id that does not exist?

    getEntry returns undefined when there is no match, so check before using it.
  2. 2. How do you hide drafts only in production builds?

    A filter such as data.draft !== true when import.meta.env.PROD keeps drafts visible in development only.
  3. 3. Where is an entry's frontmatter data available?

    Validated schema fields live under entry.data.
  4. 4. What is reference() used for in a schema?

    references store an id and let you resolve the related entry later, failing the build if it is missing.

Summary

  • getCollection(name, filter?) returns all entries; getEntry returns one; getEntries resolves several references.
  • Entry content lives in entry.data, typed by your schema.
  • Filter drafts with import.meta.env.PROD, then sort explicitly (for example by pubDate).
  • Group with ordinary JavaScript, and build pages with getStaticPaths plus render().
  • reference() links collections and catches broken links at build time.

Next: Rendering Entries, MDX and Markdown Plugins