Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. Download free →
CLSkills
DatabaseintermediateNew

MongoDB Aggregation

Share

Build MongoDB aggregation pipelines with stages and operators

Works with OpenClaude

You 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 --version to verify MongoDB Shell is installed
  • Confirm your MongoDB server is running with mongosh connection test
  • Check your collection exists with db.getCollection("collectionName").countDocuments()

Steps

  1. Connect to MongoDB using mongosh and select your database with use myDatabase
  2. Start your aggregation pipeline with db.collection.aggregate([]) — the array holds all stages
  3. Add a $match stage first to filter documents: { $match: { status: "active" } }
  4. Use $group to aggregate values by field: { $group: { _id: "$category", total: { $sum: "$amount" } } }
  5. Apply $project to reshape documents and include/exclude fields: { $project: { name: 1, total: 1, _id: 0 } }
  6. Sort results with $sort: { $sort: { total: -1 } } — use 1 for ascending, -1 for descending
  7. Limit output using $limit: { $limit: 10 } to get top N results
  8. 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

Quick Info

CategoryDatabase
Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
mongodbaggregationpipelines

Install command:

curl -o ~/.claude/skills/mongodb-aggregation.md https://clskills.in/skills/database/mongodb-aggregation.md

Related Database Skills

Other Claude Code skills in the same category — free to download.

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.