12 MongoDB Prompts to Design Smarter Schemas, Wield Aggregations, and Fix Slow Queries

MongoDB is a powerhouse for modern applications, but it's also a double-edged sword. Its flexible document model lets you iterate quickly, yet without a disciplined approach to schema design and query optimization, you'll end up with a database that's slow, bloated, and a nightmare to maintain. I've spent years working with MongoDB in production, and I've learned that the difference between a database that hums and one that crawls often comes down to a few key decisions made early on.

That's why I've curated this list of 12 prompts—each one a battle-tested request you can use with an AI assistant or as a mental checklist. They cover the three pillars of MongoDB mastery: schema design, aggregation pipelines, and query optimization. Whether you're a beginner who's just installed MongoDB or a seasoned pro looking to refine your skills, these prompts will help you get more out of your database.

Let's dive in.

1. Schema Design: The Art of Modeling

Prompt 1: "Design a MongoDB schema for a multi-tenant SaaS application that tracks user activities and generates daily reports. Consider data access patterns, sharding, and indexing. Provide a document structure with example JSON."

Why it works: This prompt forces you to think about the big picture. In a multi-tenant app, you need to decide whether to embed or reference tenant data, how to handle tenant isolation (e.g., a tenantId field), and how to structure collections for efficient reporting. The AI will typically suggest a pattern like this:

{
  "_id": ObjectId("..."),
  "tenantId": "tenant_123",
  "userId": "user_456",
  "action": "page_view",
  "metadata": {
    "url": "/home",
    "referrer": "https://google.com"
  },
  "createdAt": ISODate("2026-09-04T10:00:00Z")
}

Example result: The AI might suggest an activities collection with a compound index on {tenantId: 1, createdAt: -1} to support both tenant-specific queries and time-range aggregations. It will also recommend a separate daily_reports collection to pre-aggregate data, reducing load on the main collection.

Prompt 2: "Compare embedding vs referencing for a blog platform where users can write posts and comment on them. Provide trade-offs and a final recommendation."

Why it works: One of the most common MongoDB design dilemmas. Embedding comments inside a post document (up to 16MB limit) is fine for small-scale, but if a post can have thousands of comments, you'll need a separate comments collection. The AI will break down the pros and cons, considering document growth, query patterns, and write amplification.

Example result: For a typical blog, the AI might recommend embedding the first few comments (for fast rendering) and then referencing a comments collection for the full list, explaining the trade-offs in terms of atomicity and performance.

Prompt 3: "I'm building an IoT system that ingests sensor data every second. How should I structure my collections to handle high write throughput and efficient time-series queries?"

Why it works: Time-series data is a classic MongoDB use case, but it requires careful design. The AI will suggest using a bucketing strategy—storing data in hourly or daily buckets to reduce the number of documents. For example:

{
  "sensorId": "sensor_001",
  "bucket": ISODate("2026-09-04T00:00:00Z"),
  "data": [
    {"t": 1693814400, "v": 23.5},
    {"t": 1693814401, "v": 23.6}
  ]
}

Example result: The AI will also recommend using the timeseries collection type introduced in MongoDB 5.0, which automatically manages bucket granularity and optimizes storage.

2. Aggregation Pipelines: From Data to Insights

Prompt 4: "Write an aggregation pipeline to calculate the total revenue per product category for the last month, including only orders with status 'completed'. Group by category and sort by revenue descending."

Why it works: This is a typical reporting query. The AI will construct a pipeline that uses $match to filter by status and date, $lookup to join with the products collection (if necessary), $unwind to deconstruct the array of items, $group to sum revenue, and $sort. Here's an example:

db.orders.aggregate([
  {
    $match: {
      status: "completed",
      orderDate: { $gte: ISODate("2026-08-01"), $lt: ISODate("2026-09-01") }
    }
  },
  {
    $lookup: {
      from: "products",
      localField: "items.productId",
      foreignField: "_id",
      as: "productInfo"
    }
  },
  { $unwind: "$productInfo" },
  {
    $group: {
      _id: "$productInfo.category",
      totalRevenue: { $sum: { $multiply: ["$items.quantity", "$items.price"] } }
    }
  },
  { $sort: { totalRevenue: -1 } }
]);

Example result: The AI might also suggest using $expr for more complex date calculations and remind you to create indexes on status and orderDate to speed up the $match stage.

Prompt 5: "I have a collection of user events. Use aggregation to find the top 5 most active users by number of events in the last 24 hours. Return their user IDs and event counts."

Why it works: This prompt tests your ability to use $group and $sort with $limit. The AI will produce:

db.events.aggregate([
  {
    $match: {
      timestamp: { $gte: new Date(Date.now() - 24*60*60*1000) }
    }
  },
  {
    $group: {
      _id: "$userId",
      count: { $sum: 1 }
    }
  },
  { $sort: { count: -1 } },
  { $limit: 5 }
]);

Example result: It will also suggest an index on {timestamp: 1, userId: 1} to optimize the $match and $group.

Prompt 6: "Explain how to use $facet to get multiple aggregations in a single query. Provide an example that returns both the total count and the average value."

Why it works: $facet allows you to run multiple pipelines in parallel, which is great for dashboards. The AI will show you how to structure the output:

db.sales.aggregate([
  {
    $facet: {
      totalCount: [{ $count: "count" }],
      averageValue: [{ $group: { _id: null, avg: { $avg: "$amount" } } }]
    }
  }
]);

Example result: This returns a document with two fields, totalCount and averageValue, each containing the results of the respective sub-pipelines.

3. Query Optimization: Making MongoDB Fly

Prompt 7: "My query on a collection with 10 million documents takes 5 seconds. How can I optimize it? The query filters by 'user_id' and sorts by 'created_at'. Provide an index strategy."

Why it works: This prompt addresses the most common performance issue: missing indexes. The AI will explain that a compound index on {user_id: 1, created_at: -1} will allow MongoDB to use the index for both filtering and sorting, avoiding an in-memory sort. It will also suggest using explain() to verify.

Example result: The AI might output:

db.collection.createIndex({ user_id: 1, created_at: -1 });

And then show you how to use explain() to check winningPlan and executionStats.

Prompt 8: "Use explain() to analyze a slow query. What fields should I look for to identify bottlenecks?"

Why it works: This prompt teaches you how to debug performance issues. The AI will tell you to look at executionStats fields like totalKeysExamined, totalDocsExamined, executionTimeMillis, and stage. A high totalDocsExamined relative to nReturned indicates a lack of selectivity. The AI will guide you to interpret the winningPlan and potentially suggest an index.

Prompt 9: "I'm using $lookup and it's slow. What are some ways to optimize it?"

Why it works: $lookup can be a performance killer if not used properly. The AI will suggest: 1) Ensure there's an index on the foreign field, 2) Use $match before $lookup to reduce the input, 3) Consider denormalizing data if $lookup is frequent, 4) Use pipeline option to filter within the $lookup. Example:

db.orders.aggregate([
  { $match: { status: "completed" } },
  {
    $lookup: {
      from: "products",
      let: { prodId: "$productId" },
      pipeline: [
        { $match: { $expr: { $eq: ["$_id", "$$prodId"] } } },
        { $project: { name: 1 } }
      ],
      as: "product"
    }
  }
]);

Example result: This ensures the $lookup only processes matching documents.

Prompt 10: "What are the signs that my MongoDB instance is running out of memory? How can I monitor it?"

Why it works: This prompt covers operational health. The AI will mention MongoDB's WiredTiger cache, which defaults to 50% of RAM minus 1GB. Signs include cache pressure in db.serverStatus(), increasing page faults, and slow queries. You can monitor via mongostat and db.currentOp(). The AI will also suggest enabling the serverStatus command and perhaps using MongoDB Atlas's built-in monitoring.

Prompt 11: "How do I handle slow aggregation pipelines that process huge datasets? Should I use $match early?"

Why it works: This prompt focuses on pipeline optimization. The AI will stress the importance of placing $match and $project as early as possible to reduce the number of documents flowing through the pipeline. It will also suggest using allowDiskUse: true for large sorts and $sort only after a $group to reduce memory.

Prompt 12: "I have a query that scans many documents but returns few. What indexes should I create? Provide a step-by-step approach."

Why it works: This prompt guides you through index creation based on query patterns. The AI will advise you to examine the query filter, sort, and projection, then create a compound index that matches. It will also remind you to remove unused indexes to reduce overhead.

Wrapping Up

MongoDB is only as powerful as the design and optimization behind it. By using these prompts as a guide, you can avoid common pitfalls and ensure your database scales gracefully. Remember: schema design is a continuous process, aggregation pipelines are your analytical toolkit, and query optimization is an ongoing practice.

If you're eager to dive deeper, I recommend consulting the official MongoDB documentation and experimenting with your own datasets. And if you're looking for a structured way to master these skills, consider enrolling in a course that offers hands-on projects—like those on Asibiont.com, where you can learn by doing.

Happy coding!

← All posts

Comments