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 }
.
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 whole collection not for special group it needs to be set to null otherwise the query will return multiple max/min results, a result for each group