Mastering MongoDB aggregation requires understanding its powerful operators, pipelines, and stages. Below are the most commonly used aggregation stages and operators with examples:
Filters documents to pass only those that match specified conditions.
db.orders.aggregate([
{ $match: { status: "shipped" } }
]);Groups documents by a specified field and performs operations like sum, average, or count.
db.orders.aggregate([
{ $group: { _id: "$customerId", totalAmount: { $sum: "$amount" } } }
]);Shapes the output documents by including, excluding, or transforming fields.
db.orders.aggregate([
{ $project: { orderId: 1, totalCost: { $multiply: ["$price", "$quantity"] } } }
]);Sorts documents in ascending (1) or descending (-1) order.
db.orders.aggregate([
{ $sort: { createdAt: -1 } }
]);Limits the number of documents and skips the specified number of documents.
db.orders.aggregate([
{ $sort: { createdAt: -1 } },
{ $limit: 5 },
{ $skip: 10 }
]);Deconstructs an array field to output a document for each element.
db.orders.aggregate([
{ $unwind: "$items" }
]);Performs a left outer join with another collection.
db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerDetails"
}
}
]);Adds or modifies fields in the output documents.
db.orders.aggregate([
{ $addFields: { totalCost: { $multiply: ["$price", "$quantity"] } } }
]);Processes multiple pipelines and outputs multiple results in one stage.
db.orders.aggregate([
{
$facet: {
totalSales: [{ $group: { _id: null, total: { $sum: "$amount" } } }],
orderCount: [{ $count: "orderCount" }]
}
}
]);Categorizes documents into groups, or "buckets," based on a field’s values.
db.orders.aggregate([
{
$bucket: {
groupBy: "$amount",
boundaries: [0, 50, 100, 200],
default: "Other",
output: { count: { $sum: 1 } }
}
}
]);Replaces the input document with a specified field.
db.orders.aggregate([
{ $replaceRoot: { newRoot: "$customerDetails" } }
]);Writes the results of the aggregation pipeline to a new collection.
db.orders.aggregate([
{ $match: { status: "shipped" } },
{ $out: "shippedOrders" }
]);- Arithmetic Operators:
$add,$subtract,$multiply,$divide - Array Operators:
$size,$arrayElemAt,$push - Comparison Operators:
$eq,$ne,$lt,$lte,$gt,$gte - Conditional Operators:
$cond,$ifNull - String Operators:
$concat,$substr,$toUpper,$toLower - Date Operators:
$dateToString,$dayOfYear,$month,$year
A pipeline to calculate total sales, average order amount, and group by customer.
db.orders.aggregate([
{ $match: { status: "shipped" } },
{
$group: {
_id: "$customerId",
totalSpent: { $sum: "$amount" },
averageOrderValue: { $avg: "$amount" },
orderCount: { $sum: 1 }
}
},
{ $sort: { totalSpent: -1 } },
{
$lookup: {
from: "customers",
localField: "_id",
foreignField: "_id",
as: "customerDetails"
}
},
{ $project: { _id: 0, customer: { $arrayElemAt: ["$customerDetails.name", 0] }, totalSpent: 1, averageOrderValue: 1, orderCount: 1 } }
]);Would you like to dive into any specific stage or operator in more detail?