【问题标题】:Query to find the min and max value of a specific column in MongoDB Compass查询以查找 MongoDB Compass 中特定列的最小值和最大值
【发布时间】:2019-10-18 10:27:28
【问题描述】:

我在 MongoDB 中有一些集合,例如像下面这样的

[
  { "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:00:00Z") },
  { "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-02-03T09:00:00Z") },
  { "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-03T09:05:00Z") },
  { "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-02-15T08:00:00Z") },
  { "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-15T09:05:00Z") }
]

我想找到“_id”或任何其他字段的最小值和最大值。我正在使用“MongoDB Compass”。我如何在 MongoDB Compass 中编写一个查询,它给出了特定列的最小值和最大值

【问题讨论】:

    标签: mongodb mongodb-compass


    【解决方案1】:

    如果您想在 filter 文本框中执行此操作,即通过查询而不是通过聚合(如 sushant 建议的那样),那么您可以按降序对目标字段进行排序并将限制设置为 1。

    示例:最低价格


    示例:最高价格

    【讨论】:

      【解决方案2】:

      您可以使用 $group 管道在聚合管道中使用 $min 和 $max 运算符作为

       collectionName.aggregate([
          {$group:{_id:null,minVal: {$min: "$price"},maxVal: {$min: "$price"},}}
         ])
      

      【讨论】:

      • 不,它在 Compass 中不起作用。基本上我想在 mongoDB compass @sushant mehta 的“过滤器”文本框上写查询
      • 我没用过罗盘,但是我们不能在罗盘中使用聚合生成器吗。docs.mongodb.com/compass/master/aggregation-pipeline-builder
      • 我不知道,我是 MongoDB 和 Compass @sushant mehta 的新手
      • 如果您只能使用查询,那么您可以对要获取其最小值和最大值的键使用限制为 1 的排序
      • 您可以查看链接以了解如何在指南针中使用聚合,只需在管道中添加上述组
      猜你喜欢
      • 1970-01-01
      • 2019-02-28
      • 2012-09-16
      • 2015-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多