Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Max and min in mongodb

I have the a collection of entries as follows:

{
  company:"C3",
  model:"M3",
  price:55600,
  discount:9,
  ...
}

and there are more than 2000 entries.

I am trying to find out max and min prices in the whole collection.

Maybe with something along the lines of:

db.collection.find({ max: { $max: "$price" }, min: { $min: "$price" } });

I'd like the output as { max: 2000, min: 5000 }.

like image 478
Mohit H Avatar asked Oct 19 '15 04:10

Mohit H


People also ask

What is MongoDB $Min?

Definition. The $min updates the value of the field to a specified value if the specified value is less than the current value of the field. The $min operator can compare values of different types, using the BSON comparison order. To specify a <field> in an embedded document or in an array, use dot notation.

How does MongoDB calculate max salary?

Step 2.1 - We will group employee by firstName and find maximum salary of each group. Step 2.2- We will use aggregate() method, $group operator and $max operator. Step 4.3 - Then we will group employee by firstName and find maximum salary of each group. Step 4.4 - We will use aggregate() method, $group operator.


1 Answers

You need to use the .aggregate() method for it to work.

db.collection.aggregate([ 
    { "$group": { 
        "_id": null,
        "max": { "$max": "$price" }, 
        "min": { "$min": "$price" } 
    }}
])

The _id field is mandatory in the $group stage and to find the max/min values for price for the hole collection not for special group it needs to be set to null otherwise the query will only return max/min for each group

like image 190
styvane Avatar answered Nov 10 '22 23:11

styvane