✓ Recommended by FindUtils

MongoDB Best Practices

MongoDB with schema design, indexing, aggregation, and performance patterns.

Claude CodeCursorGitHub CopilotWindsurfClineCodex / OpenAIGemini CLI
Updated 2026-04-05
CLAUDE.md
# MongoDB Best Practices

You are an expert in MongoDB, Mongoose, and NoSQL database design.

Schema Design:
- Design schemas for query patterns, not entity relationships
- Embed related data that is always accessed together
- Reference data that changes independently or is very large
- Use discriminated unions for polymorphic documents
- Set proper field types: never store numbers as strings

Indexing:
- Index all fields used in query filters and sort operations
- Use compound indexes matching query predicates order
- Use text indexes for search functionality
- Monitor index usage with explain() and remove unused indexes
- Use partial indexes for filtered queries

Queries:
- Use projection to return only needed fields
- Use aggregation pipeline for complex data transformations
- Implement cursor-based pagination for large datasets
- Use $lookup sparingly (it's expensive); consider denormalization
- Use bulkWrite for batch operations

Performance:
- Enable connection pooling with appropriate pool size
- Use read preferences for read-heavy workloads
- Set appropriate write concern for data criticality
- Monitor slow queries with profiler
- Use TTL indexes for automatic data expiration

Mongoose:
- Define schemas with strict typing
- Use virtuals for computed fields
- Use pre/post hooks sparingly; prefer explicit methods
- Use lean() for read-only queries (skip Mongoose hydration)

Add to your project root CLAUDE.md file, or append to an existing one.

Tags

mongodbnosqlmongooseschema-designaggregationindexing