0
0
MongodbHow-ToBeginner · 2 min read

MongoDB Query to Find Maximum Value in a Collection

Use the MongoDB aggregation pipeline with $group and $max to find the maximum value, for example: db.collection.aggregate([{ $group: { _id: null, maxValue: { $max: "$fieldName" } } }]).
📋

Examples

Input[{ "score": 10 }, { "score": 20 }, { "score": 15 }]
Output[{ "_id": null, "maxValue": 20 }]
Input[{ "price": 100 }, { "price": 50 }, { "price": 150 }]
Output[{ "_id": null, "maxValue": 150 }]
Input[]
Output[]
🧠

How to Think About It

To find the maximum value in MongoDB, think of grouping all documents together and then picking the highest value of the field you want. The $group stage collects all documents, and $max finds the largest value among them.
📐

Algorithm

1
Select the collection to query.
2
Use the aggregation pipeline with a <code>$group</code> stage.
3
Set <code>_id</code> to null to group all documents together.
4
Use <code>$max</code> on the target field to find the maximum value.
5
Return the result with the maximum value.
💻

Code

mongodb
db.collection.aggregate([
  { $group: { _id: null, maxValue: { $max: "$score" } } }
])
Output
[{ "_id": null, "maxValue": 20 }]
🔍

Dry Run

Let's trace finding the max score from documents with scores 10, 20, and 15.

1

Group all documents

All documents are grouped together with _id: null.

2

Calculate max value

MongoDB compares scores 10, 20, and 15 and finds 20 as max.

3

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

Sort and limit
mongodb
db.collection.find().sort({ score: -1 }).limit(1)
This returns the document with the highest score but includes all fields, not just the max value.
Map-reduce
mongodb
db.collection.mapReduce(
  function() { emit(1, this.score); },
  function(key, values) { return Math.max.apply(null, values); },
  { out: { inline: 1 } }
)
More complex and slower than aggregation, but useful for custom max calculations.

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.

ApproachTimeSpaceBest For
Aggregation with $maxO(n)O(1)Simple max value queries
Sort and limitO(n log n)O(1)Getting full document with max field
Map-reduceO(n)O(n)Complex custom max calculations
💡
Use aggregation with $group and $max for a simple and efficient max value query.
⚠️
Trying to use find() with $max directly, which is not supported in MongoDB queries.