#How do I query content collections
2 messages · Page 1 of 1 (latest)
Astro provides two functions to query a collection and return one (or more) content entries: getCollection() and getEntry().
The getCollection() function retrieves a list of content collection entries by collection name. It returns all items in the collection by default, and accepts an optional filter function to narrow by entry properties. This allows you to query for only some items in a collection based on id, slug, or frontmatter values via the data object.
Here's an example of how to use getCollection():
import { getCollection } from 'astro:content';
// Get all `src/content/blog/` entries
const allBlogPosts = await getCollection('blog');
// Only return posts with `draft: true` in the frontmatter
const draftBlogPosts = await getCollection('blog', ({ data }) => {
return data.draft === true;
});
The getEntry() function retrieves a single collection entry by collection name and either the entry id (for type: 'data' collections) or entry slug (for type: 'content' collections).
Here's an example of how to use getEntry():
import { getEntry } from 'astro:content';
// Get `src/content/blog/enterprise.md`
const enterprisePost = await getEntry('blog', 'enterprise');
// Get `src/content/captains/picard.yaml`
const picardProfile = await getEntry('captains', 'picard');
// Get the profile referenced by `data.captain`
const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain);