MongoDB Query to Find Minimum Value in a Collection
db.collection.find().sort({field: 1}).limit(1) to get the document with the minimum value in a field, or use db.collection.aggregate([{ $group: { _id: null, minValue: { $min: "$field" }}}]) to get the minimum value directly.Examples
How to Think About It
Algorithm
Code
use testdb; // Sample documents // { "score": 10 }, { "score": 5 }, { "score": 8 } // Method 1: Find document with minimum score const minDoc = db.scores.find().sort({ score: 1 }).limit(1).toArray(); printjson(minDoc); // Method 2: Find minimum score value only const minValue = db.scores.aggregate([ { $group: { _id: null, minScore: { $min: "$score" } } } ]).toArray(); printjson(minValue);
Dry Run
Let's trace finding the minimum score from documents [{score: 10}, {score: 5}, {score: 8}] using sorting.
Sort documents by score ascending
[{score: 5}, {score: 8}, {score: 10}]
Limit to first document
{score: 5}
| Step | Operation | Result |
|---|---|---|
| 1 | Sort by score ascending | [{score: 5}, {score: 8}, {score: 10}] |
| 2 | Limit to 1 document | {score: 5} |
Why This Works
Step 1: Sorting to find minimum
Sorting documents by the field in ascending order puts the smallest value first, so limiting to one document returns the minimum.
Step 2: Aggregation with $min
The aggregation framework's $min operator calculates the smallest value of a field across all documents efficiently.
Alternative Approaches
db.scores.findOne({}, { sort: { score: 1 } })db.scores.mapReduce( function() { emit(1, this.score); }, function(key, values) { return Math.min.apply(null, values); }, { out: { inline: 1 } } )
Complexity: O(n) time, O(1) space
Time Complexity
Both sorting and aggregation scan all documents once, so time is proportional to the number of documents, O(n).
Space Complexity
Aggregation and sorting use constant extra space, O(1), as they process documents in place or with indexes.
Which Approach is Fastest?
Using an index on the field and findOne with sort is fastest for getting the minimum document; aggregation is best for just the minimum value.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sorting with find().sort().limit(1) | O(n) | O(1) | Getting full document with minimum value |
| Aggregation with $min | O(n) | O(1) | Getting minimum value only |
| findOne with sort | O(log n) with index | O(1) | Fastest for minimum document if indexed |