Нахождение максимального значения в многомерном в mongodb - PullRequest
2 голосов
/ 30 мая 2011

если у меня есть эта коллекция

{ "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?

1 Ответ

7 голосов
/ 30 мая 2011
// 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...