⏱️3 min read · 648 words
MongoDB is the world’s most popular NoSQL database. In 2026, MongoDB 8.0 brings major performance improvements and better developer tools. This complete guide covers everything from your first document to production-grade MongoDB architecture.
📋 Table of Contents
Warum MongoDB?
- Flexibles Schema– keine Migrationen für sich entwickelnde Datenmodelle
- JSON-ähnliche Dokumente– natürliche Passform für JavaScript/Python-APIs
- Horizontale Skalierung– integriertes Sharding für große Datenmengen
- Umfangreiche Abfragesprache– Aggregationspipelines konkurrieren bei der Analyse mit SQL
- Atlas-Vektorsuche— Semantische Suche nach KI-Anwendungen
Installation
# macOS
brew tap mongodb/brew && brew install mongodb-community@8.0
brew services start mongodb-community@8.0
# Ubuntu 24.04
curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg --dearmor
echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
sudo apt update && sudo apt install -y mongodb-org
sudo systemctl start mongod
# Connect to shell
mongosh
Kern-CRUD-Operationen
// Switch database
use techpulse_db
// INSERT
db.users.insertOne({
name: "Alice",
email: "alice@example.com",
skills: ["Python", "React"],
createdAt: new Date()
})
db.posts.insertMany([
{ title: "React Guide", views: 1500, tags: ["react", "js"] },
{ title: "Python Guide", views: 2300, tags: ["python", "backend"] }
])
// FIND
db.users.find({ skills: "Python" }) // match array element
db.posts.find(
{ views: { $gt: 1000 } }, // filter
{ title: 1, views: 1, _id: 0 } // projection
)
// UPDATE
db.users.updateOne(
{ email: "alice@example.com" },
{ $set: { role: "senior" }, $push: { skills: "Go" } }
)
db.posts.updateMany(
{ tags: "python" },
{ $inc: { views: 100 } }
)
// DELETE
db.users.deleteOne({ email: "alice@example.com" })
Indizes für Leistung
// Check slow queries
db.posts.find({ title: "React Guide" }).explain("executionStats")
// Create indexes
db.users.createIndex({ email: 1 }, { unique: true })
db.posts.createIndex({ tags: 1, views: -1 }) // compound
db.articles.createIndex({ title: "text" }) // full-text search
db.events.createIndex({ createdAt: 1 },
{ expireAfterSeconds: 2592000 }) // TTL: 30 days
// Always create indexes before going to production
db.users.getIndexes()
Aggregationspipeline
// Sales report: revenue by category
db.orders.aggregate([
{ $match: { status: "completed", createdAt: { $gte: new Date("2026-01-01") } } },
{ $unwind: "$items" },
{ $group: {
_id: "$items.category",
totalRevenue: { $sum: { $multiply: ["$items.price", "$items.qty"] } },
count: { $sum: 1 }
}},
{ $sort: { totalRevenue: -1 } },
{ $limit: 10 },
{ $project: { category: "$_id", revenue: { $round: ["$totalRevenue", 2] }, _id: 0 }}
])
Python mit PyMongo und Motor (Async)
from pymongo import MongoClient, ASCENDING
from datetime import datetime
# Sync
client = MongoClient("mongodb://localhost:27017/")
db = client.techpulse_db
users = db.users
result = users.insert_one({"name": "Alice", "createdAt": datetime.utcnow()})
alice = users.find_one({"name": "Alice"}, {"_id": 0})
users.update_one({"name": "Alice"}, {"$set": {"active": True}})
# Async with Motor (for FastAPI)
import motor.motor_asyncio
async_client = motor.motor_asyncio.AsyncIOMotorClient("mongodb://localhost:27017")
async_db = async_client.techpulse_db
async def create_user(data: dict) -> str:
result = await async_db.users.insert_one(data)
return str(result.inserted_id)
async def list_users(page: int = 1) -> list:
cursor = async_db.users.find().skip((page-1)*20).limit(20)
return await cursor.to_list(length=20)
Datenmodellierung: Einbetten vs. Referenz
// Embed when reading together (1-to-few)
{
_id: ObjectId("..."),
title: "MongoDB Guide",
author: { name: "Alice", email: "alice@blog.com" }, // embedded
tags: ["mongodb", "nosql"] // embedded
}
// Reference when shared/large (1-to-many)
// posts: { authorId: ObjectId("user1") }
// Look up with $lookup
db.posts.aggregate([
{ $lookup: {
from: "users",
localField: "authorId",
foreignField: "_id",
as: "author"
}},
{ $unwind: "$author" }
])
Best Practices für die Produktion
- Verwenden Sie Replikatsätze– mindestens 3 Knoten für HA
- Authentifizierung aktivieren– Führen Sie MongoDB niemals ohne Authentifizierung aus
- Dokumente validieren– Verwenden Sie JSON Schema oder Pydantic
- Überwachen Sie langsame Abfragen— Profiler aktivieren, Atlas-Überwachung verwenden
- Begrenzen Sie die Dokumentgröße– Bleiben Sie deutlich unter der BSON-Grenze von 16 MB
- Atlas für die Produktion— Managed Service mit Backups, Skalierung, Überwachung
# Atlas connection
MONGO_URI = "mongodb+srv://user:pass@cluster.mongodb.net/mydb?retryWrites=true&w=majority"
client = MongoClient(MONGO_URI)
MongoDB 8.0 im Jahr 2026 ist die beste Dokumentendatenbank für flexible, schnelle Anwendungen. Beginnen Sie einfach, erstellen Sie geeignete Indizes und nutzen Sie die Aggregationspipeline für Analysen. Kombinieren Sie es mit Atlas Vector Search für eine KI-gestützte semantische Suche in Ihren Apps.
🔗 Share this article
✍️ Leave a Comment