0
0
MongodbHow-ToBeginner · 2 min read

MongoDB Query to Find Minimum Value in a Collection

Use 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

InputDocuments: [{score: 10}, {score: 5}, {score: 8}]
OutputMinimum score document: {score: 5}
InputDocuments: [{price: 100}, {price: 50}, {price: 75}]
OutputMinimum price value: 50
InputDocuments: []
OutputNo documents found, result is empty
🧠

How to Think About It

To find the minimum value in MongoDB, you can either sort the documents by the field in ascending order and pick the first one, or use the aggregation framework's $min operator to calculate the minimum value directly from all documents.
📐

Algorithm

1
Choose the field to find the minimum value for.
2
If you want the whole document with the minimum value, sort by that field ascending and limit to 1.
3
If you want just the minimum value, use aggregation with $group and $min on the field.
4
Run the query and return the result.
💻

Code

mongodb
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);
Output
[ { "_id" : ObjectId("...") , "score" : 5 } ] [ { "_id" : null, "minScore" : 5 } ]
🔍

Dry Run

Let's trace finding the minimum score from documents [{score: 10}, {score: 5}, {score: 8}] using sorting.

1

Sort documents by score ascending

[{score: 5}, {score: 8}, {score: 10}]

2

Limit to first document

{score: 5}

StepOperationResult
1Sort by score ascending[{score: 5}, {score: 8}, {score: 10}]
2Limit 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

Using findOne with sort
mongodb
db.scores.findOne({}, { sort: { score: 1 } })
Simpler syntax to get the document with minimum value, but returns only one document.
Using mapReduce
mongodb
db.scores.mapReduce(
  function() { emit(1, this.score); },
  function(key, values) { return Math.min.apply(null, values); },
  { out: { inline: 1 } }
)
More complex and less efficient than aggregation; useful for custom calculations.

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.

ApproachTimeSpaceBest For
Sorting with find().sort().limit(1)O(n)O(1)Getting full document with minimum value
Aggregation with $minO(n)O(1)Getting minimum value only
findOne with sortO(log n) with indexO(1)Fastest for minimum document if indexed
💡
Use aggregation with $min for just the minimum value and sorting with limit for the full document.
⚠️
Trying to use find() with $min directly, which is not supported without aggregation.