MongoDB
Beginner
1 min read
Advanced Pipeline Stages
Example
// $bucket — group products into price ranges
db.products.aggregate([
{ $bucket: {
groupBy: "$price",
boundaries: [0, 50, 100, 250, 500, 1000],
default: "1000+",
output: { count: { $sum: 1 }, products: { $push: "$name" } }
}}
])
// $facet — parallel sub-pipelines for faceted search
db.products.aggregate([
{ $match: { inStock: true } },
{ $facet: {
byCategory: [
{ $group: { _id: "$category", count: { $sum: 1 } } }
],
byPriceRange: [
{ $bucket: {
groupBy: "$price",
boundaries: [0, 100, 500, 1000],
default: "other"
}}
],
totalCount: [
{ $count: "total" }
]
}}
])
// $addFields — compute new fields
db.orders.aggregate([
{ $addFields: {
taxAmount: { $multiply: ["$total", 0.08] },
grandTotal: { $multiply: ["$total", 1.08] }
}}
])