Master MongoDB query language, aggregation pipelines, and complex data retrieval. Learn advanced filtering, pipeline stages, data transformation, and query optimization techniques for analytics and reporting.
Master MongoDB query language and aggregation pipelines for complex data retrieval and analytics. Build multi-stage pipelines with filtering, grouping, joins, and text search to transform data for real-time reporting and dashboards.
/plugin marketplace add pluginagentmarketplace/custom-plugin-mongodb/plugin install mongodb-developer-plugin@pluginagentmarketplace-mongodbsonnetMaster complex queries, aggregation pipelines, and data transformation for real-time analytics.
This agent specializes in MongoDB's powerful query language and aggregation framework, enabling you to retrieve, filter, transform, and analyze data with sophisticated multi-stage pipelines. Perfect for building analytics engines, reporting systems, and complex data processing workflows.
You'll learn: Query syntax, all operators, projection techniques, sorting strategies, pagination patterns, aggregation stages, pipeline optimization, analytics queries, reporting patterns, and performance tuning.
Focus on fundamental find operations and basic filtering:
Example: Find active users created in last 30 days, sorted by name
db.users.find(
{
status: "active",
createdAt: { $gte: new Date(Date.now() - 30*24*60*60*1000) }
},
{ projection: { name: 1, email: 1, status: 1 } }
).sort({ name: 1 }).limit(100)
Master aggregation pipeline basics and complex filtering:
Example: Group sales by product and calculate monthly revenue
db.orders.aggregate([
{ $match: { status: "completed", date: { $gte: ISODate("2024-01-01") } } },
{ $unwind: "$items" },
{ $group: {
_id: "$items.productId",
totalQuantity: { $sum: "$items.quantity" },
totalRevenue: { $sum: "$items.price" },
orderCount: { $sum: 1 }
}
},
{ $sort: { totalRevenue: -1 } },
{ $limit: 10 }
])
Optimize complex analytics and reporting pipelines:
Example: Multi-faceted product analytics with related data
db.products.aggregate([
{ $match: { status: "active" } },
{ $lookup: { from: "reviews", localField: "_id", foreignField: "productId", as: "reviews" } },
{ $facet: {
"topRated": [
{ $sort: { "reviews.rating": -1 } },
{ $limit: 10 }
],
"byCategory": [
{ $group: { _id: "$category", count: { $sum: 1 } } }
],
"priceDistribution": [
{ $bucket: { groupBy: "$price", boundaries: [0, 50, 100, 500, 1000], default: "Other" } }
]
}
}
])
Build a multi-faceted product search with filters, text search, and sorting:
// Find products matching text search, within price range, sorted by rating
db.products.find({
$text: { $search: "laptop gaming" },
price: { $gte: 500, $lte: 2000 },
inStock: true
})
.sort({ rating: -1, createdAt: -1 })
.limit(20)
Aggregate user metrics for dashboard with time-series data:
// Monthly user growth, activity stats, and retention metrics
db.users.aggregate([
{ $match: { createdAt: { $gte: ISODate("2024-01-01") } } },
{ $group: {
_id: {
$dateToString: { format: "%Y-%m", date: "$createdAt" }
},
newUsers: { $sum: 1 },
activeUsers: { $sum: { $cond: [{ $gte: ["$lastLogin", new Date(Date.now() - 30*24*60*60*1000)] }, 1, 0] } }
}
},
{ $sort: { _id: 1 } }
])
Join orders with products and calculate business metrics:
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $unwind: "$items" },
{ $lookup: { from: "products", localField: "items.productId", foreignField: "_id", as: "productData" } },
{ $group: {
_id: "$customerId",
totalSpent: { $sum: { $multiply: ["$items.quantity", "$items.unitPrice"] } },
ordersCount: { $sum: 1 },
favoriteProduct: { $first: "$productData.name" }
}
},
{ $match: { totalSpent: { $gt: 1000 } } },
{ $sort: { totalSpent: -1 } }
])
Find similar products using aggregation and filtering:
db.products.aggregate([
{ $match: { _id: ObjectId("...") } }, // User viewed product
{ $lookup: { from: "products", let: { category: "$category" }, pipeline: [
{ $match: { $expr: { $eq: ["$category", "$$category"] }, _id: { $ne: ObjectId("...") } } },
{ $addFields: { score: { $add: ["$rating", { $divide: ["$reviewCount", 100] }] } } },
{ $sort: { score: -1 } },
{ $limit: 5 }
], as: "recommendations"
}
])
// ❌ Wrong: Mixing include/exclude (except _id)
db.users.find({}, { name: 1, email: 0 }) // ERROR!
// ✅ Correct: Either include or exclude fields
db.users.find({}, { name: 1, email: 1 }) // Include fields
db.users.find({}, { password: 0, token: 0 }) // Exclude sensitive fields
// ❌ Wrong: $lookup before $match (processes all documents)
db.orders.aggregate([
{ $lookup: { from: "products", ... } },
{ $match: { "product.price": { $gt: 100 } } } // Too late!
])
// ✅ Correct: $match first to reduce documents
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $lookup: { from: "products", ... } }
])
// ❌ Wrong: Exploding 10k items without limit
db.orders.aggregate([
{ $unwind: "$items" }, // Creates 10k documents from 1
{ $group: { _id: "$items.id", count: { $sum: 1 } } }
])
// ✅ Correct: Filter before $unwind
db.orders.aggregate([
{ $match: { date: { $gte: ISODate("2024-01-01") } } },
{ $unwind: "$items" },
{ $match: { "items.price": { $gt: 100 } } }
])
// ❌ Wrong: Large sort without index (memory-intensive)
db.users.find().sort({ email: 1 }).toArray()
// ✅ Correct: Create index first
db.users.createIndex({ email: 1 })
db.users.find().sort({ email: 1 }).toArray()
// ❌ Wrong: $lookup without proper field mapping
db.orders.aggregate([
{ $lookup: { from: "users", localField: "userId", foreignField: "_id" } }
])
// ✅ Correct: Specify output array name
db.orders.aggregate([
{ $lookup: { from: "users", localField: "userId", foreignField: "_id", as: "userDetails" } }
])
Q: What's the difference between find() and aggregate()? A: find() is for simple queries, aggregate() is for complex multi-stage transformations. Use aggregate for analytics, reporting, and data transformation. Use find() for simple CRUD.
Q: How do I join collections? A: Use $lookup in aggregation pipeline to join data from another collection. Specify localField, foreignField, and output array name.
Q: Can I update documents with aggregation? A: No, aggregation is read-only. Use $out to write results to new collection, or updateMany() for direct updates.
Q: How do I improve slow aggregation queries? A: Use explain("executionStats"), ensure $match is early, create indexes on filter fields, avoid $unwind on large arrays, and limit $lookup operations.
Q: What's the maximum number of pipeline stages? A: No hard limit, but performance degrades with many stages. Generally keep under 20 stages and optimize early stages.
Q: How do I handle null/missing fields in queries? A: Use $exists operator to filter by presence/absence, use $ifNull in aggregation to provide defaults, or use $cond for conditional logic.
Q: Can I paginate aggregation results? A: Yes, use $skip and $limit stages. For better performance on large datasets, use range-based pagination with $gte/$lt filters.
Ready to build powerful queries and analytics? 🚀
You are an elite AI agent architect specializing in crafting high-performance agent configurations. Your expertise lies in translating user requirements into precisely-tuned agent specifications that maximize effectiveness and reliability.