0
0
MongoDBquery~5 mins

$min and $max accumulators in MongoDB

Choose your learning style9 modes available
Introduction

These accumulators help find the smallest or largest value in a group of data. They make it easy to get minimum or maximum values from many records.

Finding the lowest price of products in a store.
Getting the highest score in a game leaderboard.
Finding the earliest or latest date in a list of events.
Determining the smallest or largest measurement in sensor data.
Syntax
MongoDB
db.collection.aggregate([
  {
    $group: {
      _id: null,
      minValue: { $min: "$fieldName" },
      maxValue: { $max: "$fieldName" }
    }
  }
])

Use $min to get the smallest value and $max to get the largest value.

The $group stage groups documents; _id: null means all documents are grouped together.

Examples
Finds the lowest and highest price from all sales records.
MongoDB
db.sales.aggregate([
  {
    $group: {
      _id: null,
      minPrice: { $min: "$price" },
      maxPrice: { $max: "$price" }
    }
  }
])
Finds the minimum and maximum score for each class separately.
MongoDB
db.students.aggregate([
  {
    $group: {
      _id: "$class",
      minScore: { $min: "$score" },
      maxScore: { $max: "$score" }
    }
  }
])
Sample Program

This example inserts some products with prices, then finds the lowest and highest price among them.

MongoDB
db.products.insertMany([
  { name: "Pen", price: 1.5 },
  { name: "Notebook", price: 3.0 },
  { name: "Eraser", price: 0.5 },
  { name: "Pencil", price: 1.0 }
])

db.products.aggregate([
  {
    $group: {
      _id: null,
      minPrice: { $min: "$price" },
      maxPrice: { $max: "$price" }
    }
  }
])
OutputSuccess
Important Notes

If the field contains non-numeric values, $min and $max will compare them based on BSON order.

Using _id: null groups all documents together; use a field name to group by categories.

Summary

$min finds the smallest value in a group.

$max finds the largest value in a group.

They are used inside the $group stage of aggregation.