Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Min and max values of an array in MongoDB?
To find the minimum and maximum values from array elements in MongoDB, use the $min and $max operators within an aggregation pipeline. These operators work on array fields to extract the smallest and largest values respectively.
Syntax
db.collection.aggregate([
{
$project: {
"minField": { $min: "$arrayField.property" },
"maxField": { $max: "$arrayField.property" }
}
}
]);
Sample Data
db.demo286.insertOne({
"details": [
{ "Value1": 70, "Value2": 50 },
{ "Value1": 30, "Value2": 36 }
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e4ac743f49383b52759cbbc")
}
View Sample Data
db.demo286.find().pretty();
{
"_id": ObjectId("5e4ac743f49383b52759cbbc"),
"details": [
{
"Value1": 70,
"Value2": 50
},
{
"Value1": 30,
"Value2": 36
}
]
}
Example: Get Min and Max Values
Find the minimum Value1 and maximum Value2 from the details array ?
db.demo286.aggregate([
{
$project: {
"name": 1,
"MinValue1": { $min: "$details.Value1" },
"MaxValue2": { $max: "$details.Value2" }
}
}
]);
{
"_id": ObjectId("5e4ac743f49383b52759cbbc"),
"MinValue1": 30,
"MaxValue2": 50
}
Key Points
-
$minand$maxwork with array fields using dot notation ($arrayField.property). - Use
$projectstage in aggregation to reshape the output with calculated min/max values. - These operators compare values across all array elements for the specified field.
Conclusion
The $min and $max operators in MongoDB aggregation pipelines efficiently extract minimum and maximum values from array elements. Use dot notation to target specific properties within nested array objects.
Advertisements
