getCollection

Load Every Entry in a Collection

getCollection

`getCollection("blog")` returns every entry, fully typed. Use it to build index pages, filter, sort.

3 min read Level 1/5 #astro#getCollection#content
What you'll learn
  • Call `getCollection`
  • Filter with a predicate
  • Sort and paginate

getCollection(name) returns an array of every entry in a collection. Each entry has id, data (validated frontmatter), and body (the raw source).

A Blog Index

---
import { getCollection } from "astro:content";

const posts = await getCollection("blog");
posts.sort((a, b) => +b.data.pubDate - +a.data.pubDate);
---

<ul>
  {posts.map(post => (
    <li>
      <a href={`/blog/${post.id}`}>{post.data.title}</a>
      <time>{post.data.pubDate.toLocaleDateString()}</time>
    </li>
  ))}
</ul>

Filtering With A Predicate

getCollection accepts a filter function:

---
const published = await getCollection("blog", post => !post.data.draft);
---

In production, Astro automatically excludes draft: true posts when configured to. The explicit filter still works during dev.

Sorting

getCollection doesn’t sort — you do it yourself:

posts.sort((a, b) => +b.data.pubDate - +a.data.pubDate);   // newest first

The Shape of an Entry

type Entry = {
  id: string;        // "hello-world"
  data: {            // your schema's shape
    title: string;
    pubDate: Date;
    tags: string[];
    // ...
  };
  body: string;      // raw markdown body
  filePath: string;  // absolute path (handy for debug)
  // for content with a render() helper, see "Rendering Content"
};

Up Next

Loading a single entry by id.

getEntry →