MongoDB mit Claude Code: Mongoose und Aggregation Pipeline 2026
MongoDB ist die führende NoSQL-Datenbank für flexible Datenmodelle — Mongoose ODM für TypeScript, komplexe Aggregation Pipelines, Indexing-Strategien und Atlas-Deployment. Claude Code kennt das MongoDB-Ökosystem und generiert robuste, performante Lösungen.
Mongoose Schema-Design mit TypeScript
SchemaTypsichere Mongoose-Modelle
# Prompt: "Erstelle Mongoose-Schema für ein Blog-System mit
# Posts, Comments (verschachtelt) und User-References"
// models/Post.ts — Claude Code generiert:
import mongoose, { Schema, Document, Model } from 'mongoose'
interface IComment {
author: mongoose.Types.ObjectId
text: string
createdAt: Date
}
interface IPost extends Document {
title: string
slug: string
content: string
author: mongoose.Types.ObjectId
tags: string[]
comments: IComment[]
publishedAt: Date | null
views: number
}
const CommentSchema = new Schema<IComment>({
author: { type: Schema.Types.ObjectId, ref: 'User', required: true },
text: { type: String, required: true, maxlength: 2000 },
createdAt: { type: Date, default: Date.now }
}, { _id: true })
const PostSchema = new Schema<IPost>({
title: { type: String, required: true, maxlength: 200 },
slug: { type: String, required: true, unique: true },
content: { type: String, required: true },
author: { type: Schema.Types.ObjectId, ref: 'User', required: true },
tags: [{ type: String, lowercase: true, trim: true }],
comments: [CommentSchema],
publishedAt: { type: Date, default: null },
views: { type: Number, default: 0 }
}, { timestamps: true })
// Indizes für Performance
PostSchema.index({ slug: 1 }) // Unique, schnelle Abfrage
PostSchema.index({ author: 1, publishedAt: -1 }) // User-Posts sortiert
PostSchema.index({ tags: 1 }) // Tag-Filter
PostSchema.index({ title: 'text', content: 'text' }) // Volltextsuche
export const Post: Model<IPost> = mongoose.model('Post', PostSchema)
CRUD-Operationen und Queries
CRUDTypische Mongoose-Queries
# Prompt: "Implementiere CRUD für Posts mit Pagination, Populate und Volltextsuche"
// Paginierte Liste mit Author-Details
const posts = await Post
.find({ publishedAt: { $ne: null }, tags: 'javascript' })
.populate('author', 'name email avatar') // Nur bestimmte Felder
.sort({ publishedAt: -1 })
.skip((page - 1) * limit)
.limit(limit)
.lean() // Schneller: Plain JS Object
// Volltextsuche (benötigt text Index)
const results = await Post.find(
{ $text: { $search: searchQuery } },
{ score: { $meta: 'textScore' } }
).sort({ score: { $meta: 'textScore' } })
// Atomic Update — View-Counter erhöhen
const post = await Post.findOneAndUpdate(
{ slug },
{ $inc: { views: 1 } }, // Atomic Increment
{ new: true } // Updated Document zurückgeben
)
// Comment hinzufügen (eingebettet)
await Post.updateOne(
{ _id: postId },
{ $push: { comments: { author: userId, text: commentText } } }
)
Performance-Tipp: Nutze
.lean() wenn du das Dokument nicht ändern musst — es gibt ein Plain JavaScript Object zurück und ist 2-5x schneller als ein Mongoose Document.Aggregation Pipeline
AggregationKomplexe Datenanalyse
# Prompt: "Erstelle eine Aggregation Pipeline für Blog-Statistiken:
# Top-Autoren nach Views, Posts pro Tag, Durchschnittliche Kommentaranzahl"
const stats = await Post.aggregate([
// Stage 1: Nur published Posts
{ $match: { publishedAt: { $ne: null } } },
// Stage 2: Nach Autor gruppieren
{ $group: {
_id: '$author',
totalViews: { $sum: '$views' },
postCount: { $sum: 1 },
avgComments: { $avg: { $size: '$comments' } },
tags: { $addToSet: '$tags' }
}},
// Stage 3: Author-Details hinzufügen
{ $lookup: {
from: 'users',
localField: '_id',
foreignField: '_id',
as: 'author'
}},
{ $unwind: '$author' },
// Stage 4: Felder umbenennen und sortieren
{ $project: {
authorName: '$author.name',
totalViews: 1,
postCount: 1,
avgComments: { $round: ['$avgComments', 1] }
}},
{ $sort: { totalViews: -1 } },
{ $limit: 10 }
])
Indexing und Performance
PerformanceIndex-Strategien für Produktion
# Compound Indizes für häufige Query-Muster:
# Query: find({ status: 'active', createdAt: { $gte: ... } }).sort({ createdAt: -1 })
PostSchema.index({ status: 1, createdAt: -1 }) // Compound Index
# Explain Plan — Query analysieren:
const plan = await Post.find({ tags: 'vue' }).explain('executionStats')
# Prüfe: totalDocsExamined vs totalDocsReturned
# Gut: beide gleich. Schlecht: viel mehr examined als returned → Index fehlt
# MongoDB Atlas Search (Vektoren + Volltext):
# Atlas Search Index erstellen für semantische Suche
# $vectorSearch Stage für AI-powered Suche
# Connection Pooling (Production):
mongoose.connect(MONGODB_URI, {
maxPoolSize: 10,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000
})
Datenbank-Modul im Kurs
Im Claude Code Mastery Kurs: vollständiges MongoDB-Modul mit Schema-Design, Aggregation Pipelines, Atlas Search, Performance-Optimierung und Production-Deployment.
14 Tage kostenlos testen →