MongoDB
Aggregation Pipeline
Build multi-stage pipelines for analytics.
By EZ4Code Team
aggregationpipelineanalytics
Code
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: {
_id: "$customerId",
total: { $sum: "$amount" },
count: { $sum: 1 }
}},
{ $sort: { total: -1 } },
{ $limit: 10 },
{ $project: {
customer: "$_id",
total: 1,
avgOrder: { $divide: ["$total", "$count"] },
_id: 0
}},
{ $lookup: {
from: "customers",
localField: "customer",
foreignField: "_id",
as: "customerInfo"
}}
]);Explanation
The aggregation pipeline chains stages that transform and combine documents. $match filters early for performance, $group computes per-key totals, and $lookup performs a left join with another collection. Order matters: filter and sort before limit to use indexes efficiently.
More MongoDB Snippets
Insert & Find
Insert documents and query a collection.
Query Operators
Use comparison, logical, array, and regex operators.
Indexes
Create single, compound, and text indexes for performance.
Update & Delete
Modify and remove documents with update operators.
Collections & Schema
Manage collections, validators, and capped collections.
Replica Set
Configure a replica set for high availability.