$min and $max accumulators in MongoDB - Time & Space Complexity
When using $min and $max accumulators in MongoDB aggregation, it's important to know how the time to find minimum or maximum values grows as data grows.
We want to understand how the work changes when the number of documents increases.
Analyze the time complexity of the following aggregation pipeline using $min and $max.
db.sales.aggregate([
{
$group: {
_id: "$store",
minSale: { $min: "$amount" },
maxSale: { $max: "$amount" }
}
}
])
This groups sales by store and finds the smallest and largest sale amount per store.
Look for repeated work done by the query.
- Primary operation: Scanning each document once to compare its amount value.
- How many times: Once per document in the collection.
As the number of documents grows, the number of comparisons grows roughly the same.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 comparisons |
| 100 | 100 comparisons |
| 1000 | 1000 comparisons |
Pattern observation: The work grows directly with the number of documents.
Time Complexity: O(n)
This means the time to find minimum and maximum values grows linearly with the number of documents.
[X] Wrong: "Using $min and $max is instant no matter how many documents there are."
[OK] Correct: MongoDB must check each document's value to find the min or max, so more documents mean more work.
Understanding how accumulators like $min and $max scale helps you explain query performance clearly and shows you grasp how databases process data.
"What if we added an index on the amount field? How would that affect the time complexity of finding $min and $max?"
Practice
$min and $max accumulators do in a MongoDB aggregation pipeline?Solution
Step 1: Understand the purpose of
$minand$max$minreturns the smallest value from the grouped documents, while$maxreturns the largest value.Step 2: Compare with other options
The other options describe different operations like average, first/last document, or sorting, which are not what$minand$maxdo.Final Answer:
$minfinds the smallest value and$maxfinds the largest value in a group. -> Option DQuick Check:
$min= smallest,$max= largest [OK]
- Confusing
$minand$maxwith average functions - Thinking they return documents instead of values
- Mixing accumulators with sorting operators
$max in a $group stage to find the highest score from a field named score?Solution
Step 1: Check the correct use of
The correct syntax requires$maxaccumulator$maxas the operator and the field name as a string with a $ prefix inside quotes: "$score".Step 2: Identify syntax errors in other options
{ $group: { _id: null, maxScore: { max: "$score" } } } misses the $ before max, { $group: { _id: null, maxScore: { $max: score } } } lacks quotes around field name, and { $group: { _id: null, maxScore: { $max: "score" } } } uses quotes without $ prefix, all invalid.Final Answer:
{ $group: { _id: null, maxScore: { $max: "$score" } } } -> Option AQuick Check:
Use$max: "$field"syntax [OK]
- Omitting $ before accumulator name
- Not quoting the field name with $
- Using field name without $ or quotes
{ "name": "Alice", "score": 85 }, { "name": "Bob", "score": 92 }, { "name": "Charlie", "score": 78 }What will be the output of this aggregation?
[{ $group: { _id: null, minScore: { $min: "$score" }, maxScore: { $max: "$score" } } }]Solution
Step 1: Identify minimum and maximum scores from documents
The scores are 85, 92, and 78. The smallest is 78 and the largest is 92.Step 2: Understand the aggregation output
The$groupstage groups all documents (_id: null) and calculatesminScoreas 78 andmaxScoreas 92.Final Answer:
{ "_id": null, "minScore": 78, "maxScore": 92 } -> Option BQuick Check:
Min = 78, Max = 92 [OK]
- Mixing up min and max values
- Assuming $min or $max returns documents instead of values
- Forgetting to use $ before field names
[{ $group: { _id: "$category", minPrice: { $min: price }, maxPrice: { $max: "$price" } } }]What is the error in this pipeline?
Solution
Step 1: Check syntax of
The$minand$maxusage$minaccumulator usespricewithout quotes and $ prefix, which is incorrect. It should be "$price".Step 2: Verify other parts of the pipeline
$maxis correctly used with "$price". Grouping by "$category" is valid. Using both accumulators together is allowed.Final Answer:
Field name 'price' in $min is missing quotes and $ prefix. -> Option AQuick Check:
Field names need "$" prefix inside accumulators [OK]
- Omitting $ before field names inside accumulators
- Thinking $min and $max cannot be used together
- Misunderstanding _id field usage in $group
region and amount. You want to find the smallest and largest sale amounts per region, but only for regions where the smallest sale is above 100. Which aggregation pipeline correctly achieves this?Solution
Step 1: Group by region and calculate min and max sales
The$groupstage groups documents byregionand calculatesminSaleandmaxSaleusing$minand$maxonamount.Step 2: Filter groups where minSale is greater than 100
The$matchstage after grouping filters groups whereminSaleis greater than 100, exactly as required.Final Answer:
[{ $group: { _id: "$region", minSale: { $min: "$amount" }, maxSale: { $max: "$amount" } } }, { $match: { minSale: { $gt: 100 } } }] -> Option CQuick Check:
Group first, then filter on aggregated minSale [OK]
- Filtering before grouping, which filters documents not groups
- Trying to filter inside $group stage incorrectly
- Filtering on maxSale instead of minSale
Ready to prove it?
Pass the test and this pattern moves unknown
