Introduction to MongoDB $min Operator
The MongoDB $min
operator is used in an aggregation pipeline to find the minimum value of a specified field in a collection and return it. This operator can be used in various query scenarios, such as finding the minimum value or earliest date.
Syntax
The syntax of the $min
operator is as follows:
{ $min: <expression> }
Where <expression>
is a field or expression used to find the minimum value.
Use Cases
The $min
operator is suitable for scenarios that require finding the minimum value of a specified field, such as:
- Finding the earliest date within a certain time range.
- Finding the lowest price of a specific product.
- Finding the minimum age of a person, and so on.
Examples
Here are three examples of the $min
operator:
Example 1: Finding the Minimum Value
Assume there is a students
collection that contains the name and age of each student. Now we want to find the student with the minimum age.
The aggregation pipeline that uses the $min
operator is as follows:
db.students.aggregate([{ $group: { _id: null, minAge: { $min: "$age" } } }])
After running the pipeline, the following result will be returned:
{ "_id": null, "minAge": 18 }
This indicates that the minimum age is 18 years old.
Example 2: Finding the Earliest Date
Assume there is an orders
collection that contains the date and amount of each order. Now we want to find the earliest order date.
The aggregation pipeline that uses the $min
operator is as follows:
db.orders.aggregate([{ $group: { _id: null, minDate: { $min: "$date" } } }])
After running the pipeline, the following result will be returned:
{ "_id": null, "minDate": ISODate("2022-01-01T00:00:00Z") }
This indicates that the earliest order date is January 1st, 2022.
Example 3: Finding the Lowest Price
Assume there is a products
collection that contains the name and price of each product. Now we want to find the cheapest product.
The aggregation pipeline that uses the $min
operator is as follows:
db.products.aggregate([{ $group: { _id: null, minPrice: { $min: "$price" } } }])
After running the pipeline, the following result will be returned:
{ "_id": null, "minPrice": 10 }
This indicates that the lowest price is 10 yuan.
Conclusion
The $min
operator is a very useful aggregation operator that can find the minimum value of a specified field in a collection and return it in an aggregation pipeline. Through the introduction and examples in this article, you can better understand how to use the $min
operator.