Build Aggregation Pipelines from CLI
Intermediate15 min
Construct and test MongoDB aggregation pipelines in mongosh for data transformation, grouping, and analysis directly from the command line.
Prerequisites
- -MongoDB 6+ with mongosh
- -A collection with sample data
Steps
1
Basic match and group pipeline
Filter documents and group them to compute aggregated values.
$ mongosh --eval 'db.orders.aggregate([{$match: {status: "completed"}}, {$group: {_id: "$customerId", totalSpent: {$sum: "$amount"}, orderCount: {$sum: 1}}}, {$sort: {totalSpent: -1}}, {$limit: 10}])' mydb
2
Use $lookup for collection joins
Join data from another collection similar to a SQL LEFT JOIN.
$ mongosh --eval 'db.orders.aggregate([{$lookup: {from: "customers", localField: "customerId", foreignField: "_id", as: "customer"}}, {$unwind: "$customer"}, {$project: {orderId: 1, amount: 1, customerName: "$customer.name"}}, {$limit: 5}])' mydb
3
Date-based aggregation with $group
Group orders by month to analyze trends over time.
$ mongosh --eval 'db.orders.aggregate([{$group: {_id: {year: {$year: "$createdAt"}, month: {$month: "$createdAt"}}, revenue: {$sum: "$amount"}, count: {$sum: 1}}}, {$sort: {"_id.year": 1, "_id.month": 1}}])' mydb
4
Use $facet for multiple aggregations in one query
Run several aggregation pipelines in parallel within a single query.
$ mongosh --eval 'db.orders.aggregate([{$facet: {byStatus: [{$group: {_id: "$status", count: {$sum: 1}}}], topCustomers: [{$group: {_id: "$customerId", total: {$sum: "$amount"}}}, {$sort: {total: -1}}, {$limit: 5}], dailyRevenue: [{$group: {_id: {$dateToString: {format: "%Y-%m-%d", date: "$createdAt"}}, revenue: {$sum: "$amount"}}}, {$sort: {_id: -1}}, {$limit: 7}]}}])' mydb
$facet runs all sub-pipelines on the same input dataset, making it efficient for dashboard-style queries.
5
Explain an aggregation pipeline
Analyze the execution plan to understand how MongoDB processes the pipeline.
$ mongosh --eval 'db.orders.explain("executionStats").aggregate([{$match: {status: "completed"}}, {$group: {_id: "$customerId", total: {$sum: "$amount"}}}])' mydb
Full Script
FAQ
Discussion
Loading comments...