Aggregation framework in MongoDB

medium · MongoDB — Documents & data modeling

🔹 1. Buckets ($bucket) What is $bucket? $bucket is used to group data into ranges (bins) . Similar to: “age groups” “price ranges” Example Idea Group users by age: db.users.aggregate([ { $bucket: { groupBy: "$age", boundaries: [0, 18, 30, 50, 100], default: "Other", output: { count: { $sum: 1 } } } } ]) What it does 0–18 → group 1 18–30 → group 2 30–50 → group 3 Counts how many users fall in each range Use Cases Age groups Salary ranges Product price categories 🔹 2. Auto Bucket ($bucketAuto) Automatically creates buckets db.users.aggregate([ { $bucketAuto: { groupBy: "$age", buckets: 3 } } ])  MongoDB decides ranges automatically 🔹 3. Facets ($facet) What is $facet? $facet is used to run multiple aggregations in parallel . Returns multiple results in one query Example Idea db.products.aggregate([ { $facet: { priceRanges: [ { $bucket: { groupBy: "$price", boundaries: [0, 100, 500, 1000] } } ], categories: [ { $group: { _id: "$category", count: { $sum: 1 } } } ] } } ]) What it does In one query: Groups products by price ranges Counts products by category Use Cases E-commerce filters (Amazon/Flipkart) Dashboards Multi-dimensional analysis

Back to MongoDB — Documents & data modeling

Browse all study material on Careeroza