Complex Query Techniques
Advanced Aggregation Strategies
1. Multi-Stage Aggregation Pipelines
graph LR
A[Input Documents] --> B[$match]
B --> C[$group]
C --> D[$project]
D --> E[$sort]
E --> F[Result Set]
Example Pipeline in LabEx Database
db.sales.aggregate([
{ $match: { year: 2023 } },
{ $group: {
_id: "$region",
totalRevenue: { $sum: "$amount" },
averageTransaction: { $avg: "$amount" }
}},
{ $project: {
region: "$_id",
totalRevenue: 1,
averageTransaction: { $round: [2] }
}},
{ $sort: { totalRevenue: -1 } }
])
2. Lookup and Join Operations
Operation |
Description |
Use Case |
$lookup |
Performs left outer join |
Combine data from multiple collections |
$unwind |
Deconstructs array fields |
Expand nested array elements |
$graphLookup |
Recursive search |
Traverse hierarchical data |
Complex Lookup Example
db.orders.aggregate([
{ $lookup: {
from: "customers",
localField: "customer_id",
foreignField: "_id",
as: "customer_details"
}},
{ $unwind: "$customer_details" },
{ $match: { "customer_details.status": "active" }}
])
3. Window Functions
graph TD
A[Window Functions] --> B[$rank]
A --> C[$dense_rank]
A --> D[$cumSum]
A --> E[$moving Average]
Ranking and Cumulative Calculations
db.sales.aggregate([
{ $setWindowFields: {
sortBy: { amount: -1 },
output: {
salesRank: { $rank: {} },
totalSalesCumulative: { $sum: "$amount" }
}
}}
])
4. Conditional Aggregations
Conditional Projection and Calculation
db.products.aggregate([
{ $project: {
name: 1,
discountedPrice: {
$cond: {
if: { $gte: ["$price", 100] },
then: { $multiply: ["$price", 0.9] },
else: "$price"
}
}
}}
])
5. Advanced Filtering Techniques
Technique |
Operator |
Description |
Regular Expressions |
$regex |
Pattern matching |
Text Search |
$text |
Full-text search |
Geospatial Queries |
$near |
Location-based filtering |
- Use indexes strategically
- Limit document processing early
- Avoid memory-intensive operations
- Use $limit and $match in early stages
Best Practices
- Break complex queries into multiple stages
- Use explain() to analyze query performance
- Leverage MongoDB's aggregation framework capabilities
- Test and optimize query complexity
By mastering these complex query techniques, you can unlock powerful data processing capabilities in MongoDB aggregation pipelines.