Die Aggregation Pipeline ist das MongoDB-Äquivalent zu SQL GROUP BY, JOIN und Subqueries. Pipeline-Stufen transformieren Daten Schritt für Schritt.
Grundlegende Pipeline¶
db.orders.aggregate([ { $match: { status: “completed”, date: { $gte: ISODate(“2024-01-01”) } } }, { $group: { _id: “$customer_id”, totalSpent: { $sum: “$amount” }, orderCount: { $count: {} } }}, { $sort: { totalSpent: -1 } }, { $limit: 10 } ]);
$lookup (JOIN)¶
db.orders.aggregate([ { $lookup: { from: “customers”, localField: “customer_id”, foreignField: “_id”, as: “customer” }}, { $unwind: “$customer” }, { $project: { orderDate: 1, amount: 1, customerName: “$customer.name” }} ]);
Wichtigste Erkenntnis¶
$match zuerst (nutzt Indizes), $group für Aggregationen, $lookup für Joins. Pipeline = SQL für MongoDB.