Skip to content

project rulesDatabasesmongodb

MongoDB Rules

Project rules for MongoDB: schema design around queries, deliberate indexes, schema validation, projections and no unbounded arrays.

npx workspacetemplates add mongodb-rules --tool claude-code

Writes 1 file to your project root

CLAUDE.mdadd to your file21 lines · 1.4 KBFile
# Project rules: MongoDB

## Schema design
- Model for the access pattern. Embed data that is read together and changes together; reference data that is shared or large. Write down each collection's read and write queries in a comment or doc.
- Never let an array grow without bound. Cap it, bucket it by time, or move the items to their own collection with a reference. Keep documents far below the 16 MB limit.
- Use consistent field names in camelCase, store dates as `Date`, money as integer minor units or `Decimal128`, and ids as `ObjectId`.

## Validation
- Define a `$jsonSchema` validator for each collection, with required fields and types. Version documents with a `schemaVersion` field and migrate lazily or with scripts.

## Indexes
- Create an index for every query that matters, following equality, sort, range order. Prefer compound indexes over many single ones, and drop unused ones. Confirm with `explain("executionStats")` that the plan uses an index and examines few documents.
- Add a TTL index for expiring data.

## Queries
- Always project only the fields you need and limit results. Use cursor pagination on an indexed field instead of large `skip` values.
- Do not build filters from raw request objects; allow-list fields to prevent operator injection.
- Use transactions only when several documents must change together.

## Checks
- Run tests against a real MongoDB instance, not a mock, and run the migration scripts twice to prove they are idempotent.

What it does

MongoDB does not force a schema, so the discipline has to come from the team. These rules ask an agent to design documents around how they are read and to say how each collection can grow.

They cover indexes, validation and query habits that keep a cluster fast as data accumulates.

Example

you › Store comments on a blog post

agent › The agent puts comments in their own collection with a postId reference and a compound index on postId and createdAt, adds a validator, and uses cursor pagination instead of embedding an array.

Questions

Is embedding always better in MongoDB?
No. Embed when data is read together and stays small. Reference it when it is large, shared or grows over time.
Why validate if the driver already types things?
Several services or scripts may write to the same collection. The validator protects the data from all of them.
  • MySQL Rules

    Project rulesmysql

    Free
  • Postgres SQL Rules

    Project rulespostgres

    Free
  • Database Connection Pooling

    SkillDatabases

    Free
  • Database Migration Safety

    SkillDatabases

    Free