Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 104 additions & 0 deletions backend/mongodb/architecture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
---
description: Vibe coding guidelines and architectural constraints for MongoDB within the backend domain.
technology: MongoDB
domain: backend
level: Senior/Architect
complexity: Advanced
topic: MongoDB Architecture
vibe_coding_ready: true
version: "7.0+"
tags: [architecture-patterns, mongodb, nosql, database, system-design, production-ready, scalable-code]
ai_role: Senior MongoDB Database Architect
last_updated: 2026-03-28
last_evolution: 2026-03-28
---

# 🏛️ MongoDB Architecture Constraints

This document provides the "executable blueprints" for MongoDB architecture, outlining folder hierarchies, request/data flows, and entity relationships to ensure AI-agent readiness.

## 📂 Folder Hierarchy Constraints

```mermaid
graph TD
classDef domain fill:#f9f,stroke:#333,stroke-width:2px;
classDef core fill:#bbf,stroke:#333,stroke-width:2px;

src[src] --> domains[domains]
src --> core[core]

domains --> user[User Domain]
domains --> order[Order Domain]

user --> schemas[schemas/]
user --> models[models/]
user --> repositories[repositories/]

core --> database[database/]
database --> connection[connection.ts]
database --> config[config.ts]

class domains,user,order,schemas,models,repositories domain;
class core,database,connection,config core;
```

## 🔄 Request / Data Flow

```mermaid
sequenceDiagram
participant Client
participant Controller
participant Service
participant Repository
participant Database

Client->>Controller: POST /api/users (DTO)
Controller->>Service: Create User (Domain Model)
Service->>Repository: Save User (Entity)
Repository->>Database: insertOne()
Database-->>Repository: Acknowledgment (ObjectId)
Repository-->>Service: Saved Entity
Service-->>Controller: Domain Response
Controller-->>Client: 201 Created (Response DTO)
```

## 🔗 Entity Relationships

```mermaid
classDiagram
class User {
+ObjectId _id
+String username
+String email
+String passwordHash
+Date createdAt
+Date updatedAt
+login()
+updateProfile()
}

class Post {
+ObjectId _id
+ObjectId authorId
+String title
+String content
+Array~ObjectId~ tags
+Date publishedAt
}

class Comment {
+ObjectId _id
+ObjectId postId
+ObjectId authorId
+String text
+Date createdAt
}

User "1" --> "*" Post : creates
User "1" --> "*" Comment : writes
Post "1" --> "*" Comment : contains
```

---

[⬆ Back to Top](#-mongodb-architecture-constraints)
102 changes: 102 additions & 0 deletions backend/mongodb/database-optimization.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
---
description: Vibe coding guidelines and database optimization constraints for MongoDB within the backend domain.
technology: MongoDB
domain: backend
level: Senior/Architect
complexity: Advanced
topic: MongoDB Database Optimization
vibe_coding_ready: true
version: "7.0+"
tags: [database-optimization, mongodb, nosql, indexing, aggregation-pipeline, system-design, production-ready, scalable-code]
ai_role: Senior MongoDB Database Architect
last_updated: 2026-03-28
last_evolution: 2026-03-28
---

# ⚡ MongoDB Database Optimization Best Practices

This document outlines indexing strategies (ESR Rule), aggregation pipeline optimization, and query tuning for enterprise-grade MongoDB environments.

## 🎯 1. The ESR (Equality, Sort, Range) Rule

When designing indexes, always follow the ESR rule to maximize efficiency.

### ❌ Bad Practice

Creating indexes randomly without understanding the query patterns.

```javascript
// A query with equality, sort, and range:
// db.orders.find({ status: "shipped", amount: { $gt: 100 } }).sort({ date: 1 })

// Bad index - Range comes before Sort
db.orders.createIndex({ status: 1, amount: 1, date: 1 })
```

### ✅ Best Practice

Create indexes following the ESR rule:
1. **E**quality fields first.
2. **S**ort fields next.
3. **R**ange fields last.

### 🚀 Solution

```javascript
// Ideal index for the ESR query
db.orders.createIndex({ status: 1, date: 1, amount: 1 })
```

---

## 🏗️ 2. Aggregation Pipeline Optimization

Pipelines process documents in stages. Optimizing the order of these stages dramatically improves performance.

### ❌ Bad Practice

Filtering data after heavy transformations or sorting large un-indexed datasets.

```javascript
db.users.aggregate([
{ $project: { name: 1, age: 1, status: 1 } },
{ $sort: { age: -1 } },
{ $match: { status: "active" } }
])
```

### ✅ Best Practice

Always use `$match` and `$sort` as early as possible in the pipeline to reduce the working set and take advantage of indexes. Use `$project` later.

### 🚀 Solution

```javascript
db.users.aggregate([
{ $match: { status: "active" } },
{ $sort: { age: -1 } },
{ $project: { name: 1, age: 1 } }
])
```

---

## 📉 3. Covered Queries

A covered query is a query that can be satisfied entirely using an index, without having to examine the actual documents.

### 🚀 Solution

If you have an index on `{ status: 1, amount: 1 }`:

```javascript
// This is a covered query because it only projects indexed fields (and explicitly excludes _id)
db.orders.find(
{ status: "shipped" },
{ status: 1, amount: 1, _id: 0 }
)
```

---

[⬆ Back to Top](#-mongodb-database-optimization-best-practices)
86 changes: 86 additions & 0 deletions backend/mongodb/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
---
description: Vibe coding guidelines and architectural constraints for MongoDB within the backend domain.
technology: MongoDB
domain: backend
level: Senior/Architect
complexity: Advanced
topic: MongoDB
vibe_coding_ready: true
version: "7.0+"
tags: [best-practices, clean-code, architecture-patterns, vibe-coding, mongodb, nosql, database, system-design, production-ready, scalable-code, document-database]
ai_role: Senior MongoDB Database Architect
last_updated: 2026-03-28
last_evolution: 2026-03-28
---

<div align="center">
<img src="https://raw.githubusercontent.com/tandpfun/skill-icons/main/icons/MongoDB.svg" width="100" alt="MongoDB Logo">

# 🍃 MongoDB Production-Ready Best Practices
</div>

---

This document establishes **best practices** for building and maintaining MongoDB databases. These constraints guarantee a scalable, highly secure, and clean architecture suitable for an enterprise-level, production-ready backend.

# ⚙️ Context & Scope
- **Primary Goal:** Provide an uncompromising set of rules and architectural constraints for MongoDB environments.
- **Target Tooling:** AI-agents (Cursor, Windsurf, Copilot, Antigravity) and Senior Database Administrators.
- **Tech Stack Version:** MongoDB 7.0+

> [!IMPORTANT]
> **Architectural Contract:** MongoDB is schema-less by nature, but production applications require strict schema validation at the database level and through ORM/ODMs like Mongoose. Never allow unstructured data to enter the persistence layer without validation.

---

## 📚 Specialized Documentation

For deep dives into specific topics, consult the specialized guides:

- 🏛️ [**Architecture & Design**](./architecture.md): Boundary definitions, entity relationships, and structural constraints.
- ⚡ [**Database Optimization**](./database-optimization.md): Indexing strategies (ESR Rule) and aggregation pipelines.
- 🔒 [**Security Best Practices**](./security-best-practices.md): RBAC, field-level encryption, and NoSQL injection prevention.

---

## 🏗️ Core Principles

### 🚨 1. Schema Validation
#### ❌ Bad Practice
```javascript
// Inserting data without validation
db.users.insertOne({ name: "John", age: -5, admin: true });
```
#### ✅ Best Practice
Implement strict schema validation using JSON Schema in MongoDB.
#### 🚀 Solution
```javascript
db.createCollection("users", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "email"],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
email: {
bsonType: "string",
pattern: "^.+@.+\\..+$",
description: "must be a valid email and is required"
},
age: {
bsonType: "int",
minimum: 0,
description: "must be an integer greater than or equal to 0"
}
}
}
}
});
```

---

[⬆ Back to Top](#-mongodb-production-ready-best-practices)
Loading
Loading