Know-How
MongoDB Aggregation Pipeline
Aggregation pipeline je MongoDB ekvivalent SQL GROUP BY, JOIN a subqueries. Pipeline stages transformují data krok za krokem.
Základní 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"
}}
]);
Klíčový takeaway
$match first (uses indexes), $group pro agregace, $lookup pro joiny. Pipeline = SQL pro MongoDB.