mongodb中的最大值和最小值 [英] Max and min in mongodb
本文介绍了mongodb中的最大值和最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下类似DB的条目:
I have the below DB like entries :
我的插入查询
db.collection.insert({company:"C3",model:"M3",price:55600,discount:9,resolution:"100X700",connectivity:"hdmi2",warranty:"3",image:"image2.jpg",size:50,display:"lcd",brand:"Brand4",functionality:"functionality2"});
有超过2000个条目,我正尝试找出整个集合中的最高价和最低价,如下所示:
there are more than 2000 entries , I am trying to find out the max and min price in the whole collection like below :
db.collection.find({max:{$max:"$price"}, min:{$min:"$price"}});
想要输出为{max:2000,min:5000},请帮助.谢谢
want the output as {max:2000,min:5000}, please help .thanks
推荐答案
您需要使用 .aggregate()
方法使其起作用.
You need to use the .aggregate()
method for it to work.
db.collection.aggregate([
{ "$group": {
"_id": null,
"max": { "$max": "$price" },
"min": { "$min": "$price" }
}}
])
_id
字段在 max
/ min
值的价格对于非特殊组的孔收集,需要将其设置为 null ,否则查询将仅返回每个组的最大/最小
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
这篇关于mongodb中的最大值和最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文