Build MongoDB aggregation pipelines with stages and operators
✓Works with OpenClaudeYou are a MongoDB database engineer. The user wants to build and execute aggregation pipelines with multiple stages and operators to transform, filter, and analyze data.
What to check first
- Run
mongosh --versionto verify MongoDB Shell is installed - Confirm your MongoDB server is running with
mongoshconnection test - Check your collection exists with
db.getCollection("collectionName").countDocuments()
Steps
- Connect to MongoDB using
mongoshand select your database withuse myDatabase - Start your aggregation pipeline with
db.collection.aggregate([])— the array holds all stages - Add a
$matchstage first to filter documents:{ $match: { status: "active" } } - Use
$groupto aggregate values by field:{ $group: { _id: "$category", total: { $sum: "$amount" } } } - Apply
$projectto reshape documents and include/exclude fields:{ $project: { name: 1, total: 1, _id: 0 } } - Sort results with
$sort:{ $sort: { total: -1 } }— use 1 for ascending, -1 for descending - Limit output using
$limit:{ $limit: 10 }to get top N results - Chain stages in order and call
.toArray()or.explain()to execute and view results
Code
const { MongoClient } = require("mongodb");
async function runAggregation() {
const client = new MongoClient("mongodb://localhost:27017");
try {
await client.connect();
const db = client.db("ecommerce");
const orders = db.collection("orders");
// Build aggregation pipeline with multiple stages
const pipeline = [
// Stage 1: Filter orders from the last 30 days
{
$match: {
createdAt: {
$gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
},
status: "completed"
}
},
// Stage 2: Group by customer and calculate totals
{
$group: {
_id: "$customerId",
totalSpent: { $sum: "$amount" },
orderCount: { $sum: 1 },
avgOrderValue: { $avg: "$amount" },
lastOrder: { $max: "$createdAt" }
}
},
// Stage 3: Filter groups with total > 500
{
$match: {
totalSpent: { $gt: 500 }
}
},
// Stage 4: Reshape output document
{
$project: {
customerId: "$_id",
totalSpent: { $round: ["$totalSpent
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Database Skills
Other Claude Code skills in the same category — free to download.
Migration Generator
Generate database migration files
Query Optimizer
Analyze and optimize slow database queries
Schema Designer
Design database schema from requirements
Seed Data Generator
Generate database seed/sample data
Index Advisor
Suggest database indexes based on query patterns
ORM Model Generator
Generate ORM models from database schema
SQL to ORM
Convert raw SQL queries to ORM syntax
Database Backup Script
Create database backup and restore scripts
Want a Database skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.