3 KiB
3 KiB
| title | aliases | tags | sources | created | updated | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Database Indexes |
|
|
|
2026-05-15 | 2026-05-15 |
Overview
Database indexes let the DB engine locate records without full-collection scans. Add index: true to any field you frequently filter or sort on.
id, createdAt, and updatedAt are indexed by default.
Single-Field Index
{
name: 'title',
type: 'text',
index: true,
}
Compound Indexes
Index multiple fields together — useful when queries filter/sort by several fields at once.
export const MyCollection: CollectionConfig = {
fields: [...],
indexes: [
{
fields: ['title', 'createdAt'],
unique: true, // optional: enforce uniqueness on the combination
},
],
}
Defined at the Collection level via the indexes array, not on individual fields.
Unique Fields
unique: true creates a collection-wide unique index — no two documents can share the same value.
Gotcha: unique on nested array/blocks fields
- Creates a unique index on the dotted path (e.g.
items.key) across the entire collection. - This is not per-document uniqueness — it prevents any two documents from having the same value at that path.
- MongoDB +
required: trueon a nested unique field: creates a non-sparse index. Documents without the array sharenull, causing a duplicate key error on the second save. Fix: removerequired: trueto restore sparse index. - For within-document array uniqueness → use a custom
validatefunction on the array field instead.
Localized Fields and MongoDB
index: trueorunique: trueon a localized field → MongoDB creates one index per locale path (slug.en,slug.da-dk, etc.).- Many locales + many indexed fields can hit MongoDB's per-collection index limit.
- Workaround: add custom MongoDB indexes for specific locale paths via migration script.
Key Takeaways
- Add
index: trueto fields used in frequentwherefilters orsortoperations. - Use Collection-level
indexes: [{ fields: [...] }]for compound indexes. unique: true= collection-wide uniqueness, not per-document array row uniqueness.- MongoDB: nested
unique+required= non-sparse index → duplicate-null bug. Removerequiredto fix. - Localized fields on MongoDB: one index per locale — watch the index limit with large locale sets.
- MongoDB Compass is the recommended GUI for visualizing and managing indexes.
Related
- wiki/payloadcms/collection-config —
indexesoption lives here - wiki/payloadcms/queries — where operators and sort that benefit from indexes
- wiki/payloadcms/localization — localized fields context
- wiki/payloadcms/production — broader performance patterns
Sources
raw/database__indexes.md— https://payloadcms.com/docs/database/indexes