【问题标题】:Finding max value in multidimensional in mongodb在mongodb中查找多维中的最大值
【发布时间】:2011-05-30 19:32:45
【问题描述】:

如果我有这个收藏

{ "humidity" : 96.5812, "temperature" : 10.5006 }
{ "humidity" : 97.1184, "temperature" : 10.2808 }
{ "humidity" : 96.2882, "temperature" : 8.4493 }
{ "humidity" : 97.8266, "temperature" : 7.4481 }
{ "humidity" : 98.9255, "temperature" : 7.2772 }
{ "humidity" : 99.4628, "temperature" : 7.3993 }
{ "humidity" : 99.4383, "temperature" : 7.4237 }
{ "humidity" : 99.6825, "temperature" : 7.1307 }
{ "humidity" : 99.5116, "temperature" : 6.1539 }
{ "humidity" : 99.8779, "temperature" : 5.4701 }

如何使用 mapreduce 获得温度的最大值和最小值?

【问题讨论】:

    标签: mongodb mapreduce


    【解决方案1】:
    // Simple map function - just returns the temperature value
    // for the record
    var map = function() {
        emit('temperature', this.temperature);
    };
    
    // A reduce function to find the minimum value in the reduced set
    var reduce_min = function(key, values) {
        var min = values[0];
        values.forEach(function(val) {
            if (val < min) min = val;
        })
        return min;
    };
    
    // A reduce function to find the maximum value in the reduced set
    var reduce_max = function(key, values) {
        var max = values[0];
        values.forEach(function(val){
            if (val > max) max = val;
        })
        return max;
    }
    
    // Use the mapReduce function to get the min and max
    var min = db.temp.mapReduce(map, reduce_min, {out:{inline:1}}).results[0].value;
    var max = db.temp.mapReduce(map, reduce_max, {out:{inline:1}}).results[0].value;
    print("Min: " + min + ", max: " + max);
    

    【讨论】:

      【解决方案2】:

      我喜欢上面的答案,但这里是为了清理您的代码而进行的小修改。这将为您提供相同的输出,但代码很小。您可以在线搜索 Math.min()Math.max() 文档。基本上这些是 javascript 函数来查找最小值和最大值。而 "..." 用于告诉 Math.min()/max() values 是一个数组

      var map = function() {
          emit('temperature', this.temperature);
      };
      
      // A reduce function to find the minimum value in the reduced set
      var reduce_min = function(key, values) {
          return Math.min(...values);
      };
      
      // A reduce function to find the maximum value in the reduced set
      var reduce_max = function(key, values) {
          return Math.max(...values);
      }
      
      // Use the mapReduce function to get the min and max
      var min = db.temp.mapReduce(map, reduce_min, {out:{inline:1}}).results[0].value;
      var max = db.temp.mapReduce(map, reduce_max, {out:{inline:1}}).results[0].value;
      print("Min: " + min + ", max: " + max);
      

      【讨论】:

        猜你喜欢
        • 2013-06-24
        • 2016-01-31
        • 1970-01-01
        • 1970-01-01
        • 2015-04-06
        • 2017-04-03
        • 2019-03-31
        • 2014-01-16
        • 2014-04-13
        相关资源
        最近更新 更多