mongodb 中的最大值和最小值 [英] Max and min in mongodb

查看:50
本文介绍了mongodb 中的最大值和最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下条目的集合:

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

并且有超过 2000 个条目.

and there are more than 2000 entries.

我试图找出整个集合中的 max min 价格.

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" } });

我希望输出为 { max: 2000, min: 5000 }.

推荐答案

您需要使用 .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 字段在 $group 阶段并找到 max/min 孔集合的价格值而不是特殊组它需要设置为 null 否则查询将只返回最大值/min 每组

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆