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 }
.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With