Optimize MongoDB Queries for Performance
Use this AI prompt to analyze MongoDB queries, detect performance issues, and suggest indexing or aggregation optimizations for faster execution.
🧠 What This Prompt Does
This prompt helps you analyze and optimize MongoDB queries by identifying slow operations, missing indexes, and inefficient filters.
It’s ideal for improving performance in large-scale datasets.
💬 The Prompt
You are a MongoDB performance specialist.
Analyze the following MongoDB query and suggest:
- Indexing strategies
- Query shape optimization
- Projection and pagination tips
- Aggregation improvements
Query:
{{mongo_query}}
⚙️ Example Input
{
"mongo_query": "db.users.find({ age: { $gte: 25 } }).sort({ createdAt: -1 })"
}
🚀 Example Output (AI Generated)
### Optimization Recommendations:
- ✅ Add index `{ age: 1, createdAt: -1 }` for combined filtering and sorting.
- ⚙️ Use projection to reduce payload: `find({}, { name: 1, age: 1, createdAt: 1 })`.
- 🔁 Use pagination with `.skip()` and `.limit()` for large datasets.
- 🧠 Consider using `aggregate()` for pre-filtered transformation stages.
📘 When to Use This Prompt
- When diagnosing slow queries in production.
- During schema design or index creation phases.
- For optimizing dashboards or analytics workloads.
💡 Best Practices
- Always project only needed fields.
- Avoid regex filters on non-indexed fields.
- Use compound indexes for combined sort/filter operations.
- Monitor performance via MongoDB Atlas or
explain().
🏁 Summary
This prompt acts as a virtual MongoDB performance consultant, suggesting real-time optimizations for query speed and efficiency.
How can I detect slow queries in MongoDB?
Use `db.setProfilingLevel()` and `explain("executionStats")` to inspect query plans and detect inefficiencies.
What’s the impact of indexes?
Proper indexing can drastically reduce query time but increases write overhead and memory usage.
Should I use aggregation pipelines?
Yes, for complex transformations. Always project only the required fields.
Advertisement
Related Prompts
Advertisement