MongoDB Query to Find Maximum Value in a Collection
$group and $max to find the maximum value, for example: db.collection.aggregate([{ $group: { _id: null, maxValue: { $max: "$fieldName" } } }]).Examples
How to Think About It
$group stage collects all documents, and $max finds the largest value among them.Algorithm
Code
db.collection.aggregate([
{ $group: { _id: null, maxValue: { $max: "$score" } } }
])Dry Run
Let's trace finding the max score from documents with scores 10, 20, and 15.
Group all documents
All documents are grouped together with _id: null.
Calculate max value
MongoDB compares scores 10, 20, and 15 and finds 20 as max.
Return result
Returns [{ _id: null, maxValue: 20 }].
| score |
|---|
| 10 |
| 20 |
| 15 |
Why This Works
Step 1: Grouping documents
Using $group with _id: null combines all documents into one group.
Step 2: Finding maximum
$max operator scans the grouped documents to find the highest value of the specified field.
Step 3: Output format
The result shows the maximum value under the field name you set, here maxValue.
Alternative Approaches
db.collection.find().sort({ score: -1 }).limit(1)db.collection.mapReduce( function() { emit(1, this.score); }, function(key, values) { return Math.max.apply(null, values); }, { out: { inline: 1 } } )
Complexity: O(n) time, O(1) space
Time Complexity
The aggregation scans all documents once to find the maximum, so it is O(n) where n is the number of documents.
Space Complexity
Only a few variables are needed to track the max value, so space is O(1).
Which Approach is Fastest?
Aggregation with $group and $max is generally faster and more readable than map-reduce or sorting with limit.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Aggregation with $max | O(n) | O(1) | Simple max value queries |
| Sort and limit | O(n log n) | O(1) | Getting full document with max field |
| Map-reduce | O(n) | O(n) | Complex custom max calculations |
$group and $max for a simple and efficient max value query.find() with $max directly, which is not supported in MongoDB queries.