Introduction to MongoDB cursor.min() Method

MongoDB is a non-relational database that supports multiple programming languages and provides many operations. Among them, the cursor.min() method is a very useful method that can find the minimum value of a specified field.

Syntax

The cursor.min() method is an option of the find() method. The syntax is as follows:

db.collection.find(query).min(field)

Here, query is the query condition, and field is the name of the field for which we need to find the minimum value.

Use Cases

We can use the cursor.min() method when we need to find the minimum value of a specified field. For example, in a collection that stores student grades, we can use this method to find the lowest score of a certain course.

Examples

Here are two examples of using the cursor.min() method:

  1. Find the lowest score of the math course in a collection that stores student grades.

    Assuming we have the following data:

    { name: "A", math: 80, english: 90 },
    { name: "B", math: 70, english: 85 },
    { name: "C", math: 60, english: 95 }
    

    We can use the following command to find the lowest score of the math course:

    db.scores.find({}).min("math")
    

    After executing this command, we can get the following result:

    { "_id": ObjectId("61e316c6f7f88b1701fe09d5"), "math": 60 }
  2. Find the address of the house with the lowest price in a collection that stores house prices.

    Assuming we have the following data:

    { address: "A1", price: 1000000 },
    { address: "B2", price: 800000 },
    { address: "C3", price: 1200000 }
    

    We can use the following command to find the address of the house with the lowest price:

    db.prices.find({}).min("price").project({ _id: 0, address: 1 })
    

    After executing this command, we can get the following result:

    { "address": "B2" }

Conclusion

By using this method, we can find the minimum value of a specified field and perform further data processing as needed. At the same time, we need to ensure that the query conditions are accurate enough when using this method to avoid scanning the entire collection, which may cause performance problems.