Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowFeatured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App Show

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
MongoDB Aggregation Pipelines

MongoDB Aggregation Pipelines

Build powerful data processing pipelines with MongoDB aggregation framework

MongoDBAggregationDatabaseAnalytics
by Antigravity Team
⭐0Stars
👁️1Views
.antigravity
# MongoDB Aggregation Pipelines

Master data processing with MongoDB aggregation using Google Antigravity IDE. This guide covers pipeline stages, optimization, and real-world patterns.

## Why MongoDB Aggregation?

MongoDB aggregation enables complex data transformations in the database. Google Antigravity IDE's Gemini 3 engine suggests optimal pipeline stages.

## Basic Pipeline Structure

```typescript
// lib/mongodb.ts
import { MongoClient, Db, Collection } from "mongodb";

const client = new MongoClient(process.env.MONGODB_URI!);
let db: Db;

export async function connectDB(): Promise<Db> {
  if (!db) {
    await client.connect();
    db = client.db(process.env.MONGODB_DATABASE);
  }
  return db;
}

export function getCollection<T>(name: string): Collection<T> {
  return db.collection<T>(name);
}
```

## Sales Analytics Pipeline

```typescript
// services/analyticsService.ts
import { getCollection } from "@/lib/mongodb";

interface SalesAnalytics {
  totalRevenue: number;
  averageOrderValue: number;
  orderCount: number;
  topProducts: Array<{ productId: string; revenue: number; quantity: number }>;
  salesByCategory: Array<{ category: string; revenue: number }>;
  salesByDay: Array<{ date: string; revenue: number; orders: number }>;
}

export async function getSalesAnalytics(
  startDate: Date,
  endDate: Date
): Promise<SalesAnalytics> {
  const orders = getCollection("orders");

  const pipeline = [
    // Match orders in date range
    {
      $match: {
        createdAt: { $gte: startDate, $lte: endDate },
        status: { $in: ["completed", "shipped", "delivered"] }
      }
    },
    // Unwind items for product-level analysis
    {
      $unwind: "$items"
    },
    // Lookup product details
    {
      $lookup: {
        from: "products",
        localField: "items.productId",
        foreignField: "_id",
        as: "product"
      }
    },
    {
      $unwind: "$product"
    },
    // Calculate item totals
    {
      $addFields: {
        itemTotal: { $multiply: ["$items.quantity", "$items.price"] },
        orderDate: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } }
      }
    },
    // Facet for multiple aggregations
    {
      $facet: {
        overview: [
          {
            $group: {
              _id: null,
              totalRevenue: { $sum: "$itemTotal" },
              totalOrders: { $addToSet: "$_id" },
              totalItems: { $sum: "$items.quantity" }
            }
          },
          {
            $project: {
              _id: 0,
              totalRevenue: 1,
              orderCount: { $size: "$totalOrders" },
              averageOrderValue: {
                $divide: ["$totalRevenue", { $size: "$totalOrders" }]
              }
            }
          }
        ],
        topProducts: [
          {
            $group: {
              _id: "$items.productId",
              productName: { $first: "$product.name" },
              revenue: { $sum: "$itemTotal" },
              quantity: { $sum: "$items.quantity" }
            }
          },
          { $sort: { revenue: -1 } },
          { $limit: 10 },
          {
            $project: {
              _id: 0,
              productId: "$_id",
              productName: 1,
              revenue: 1,
              quantity: 1
            }
          }
        ],
        salesByCategory: [
          {
            $group: {
              _id: "$product.category",
              revenue: { $sum: "$itemTotal" },
              count: { $sum: 1 }
            }
          },
          { $sort: { revenue: -1 } },
          {
            $project: {
              _id: 0,
              category: "$_id",
              revenue: 1,
              count: 1
            }
          }
        ],
        salesByDay: [
          {
            $group: {
              _id: "$orderDate",
              revenue: { $sum: "$itemTotal" },
              orders: { $addToSet: "$_id" }
            }
          },
          { $sort: { _id: 1 } },
          {
            $project: {
              _id: 0,
              date: "$_id",
              revenue: 1,
              orders: { $size: "$orders" }
            }
          }
        ]
      }
    }
  ];

  const [result] = await orders.aggregate(pipeline).toArray();

  return {
    ...result.overview[0],
    topProducts: result.topProducts,
    salesByCategory: result.salesByCategory,
    salesByDay: result.salesByDay
  };
}
```

## User Activity Pipeline

```typescript
export async function getUserActivityStats(userId: string) {
  const events = getCollection("events");

  const pipeline = [
    {
      $match: {
        userId,
        createdAt: { $gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) }
      }
    },
    {
      $group: {
        _id: {
          type: "$type",
          day: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } }
        },
        count: { $sum: 1 },
        metadata: { $push: "$metadata" }
      }
    },
    {
      $group: {
        _id: "$_id.type",
        dailyStats: {
          $push: {
            date: "$_id.day",
            count: "$count"
          }
        },
        totalCount: { $sum: "$count" }
      }
    },
    {
      $project: {
        _id: 0,
        eventType: "$_id",
        totalCount: 1,
        dailyStats: 1,
        avgPerDay: { $divide: ["$totalCount", 30] }
      }
    }
  ];

  return events.aggregate(pipeline).toArray();
}
```

## Text Search with Aggregation

```typescript
export async function searchProducts(query: string, filters: ProductFilters) {
  const products = getCollection("products");

  const pipeline = [
    {
      $search: {
        index: "product_search",
        compound: {
          must: [
            {
              text: {
                query,
                path: ["name", "description", "tags"],
                fuzzy: { maxEdits: 1 }
              }
            }
          ],
          filter: filters.category ? [
            { equals: { path: "category", value: filters.category } }
          ] : []
        }
      }
    },
    {
      $addFields: {
        score: { $meta: "searchScore" }
      }
    },
    {
      $match: filters.priceRange ? {
        price: { $gte: filters.priceRange.min, $lte: filters.priceRange.max }
      } : {}
    },
    { $skip: filters.offset || 0 },
    { $limit: filters.limit || 20 }
  ];

  return products.aggregate(pipeline).toArray();
}
```

## Best Practices

- Use indexes to support aggregation stages
- Apply $match early to filter data
- Use $project to reduce document size
- Leverage $facet for multiple aggregations
- Consider memory limits for large datasets
- Use explain() to optimize pipelines

Google Antigravity IDE provides MongoDB aggregation patterns and automatically suggests pipeline optimizations for your queries.

When to Use This Prompt

This MongoDB prompt is ideal for developers working on:

  • MongoDB applications requiring modern best practices and optimal performance
  • Projects that need production-ready MongoDB code with proper error handling
  • Teams looking to standardize their mongodb development workflow
  • Developers wanting to learn industry-standard MongoDB patterns and techniques

By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their mongodb implementations.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the MongoDB code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this MongoDB prompt commercially?

Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.

Which AI assistants work best with this prompt?

This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.

How do I customize this prompt for my specific needs?

You can modify the prompt by adding specific requirements, constraints, or preferences. For MongoDB projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...