0
votes

I've got a database with pre-aggregated metrics similar to the one outlined in this use case: http://docs.mongodb.org/manual/use-cases/pre-aggregated-reports/

I have a daily collection with a subdocument for hour and minute metrics, and a 'metadata.date' entry for midnight on the day it represents. I also have a monthly collection with a day subdocument for each day.

If I want to get an average of a metric over the past eight or so days how can I do that with the aggregation framework? Is the aggregation framework not the right tool for this since it's already pre-aggregated?

1

1 Answers

0
votes

I ended up using map/reduce for this:

map:

var map = function(){
          for(x in this.hour){
              var key = this.metadata.port_name;
              var value = {
                  count: 1,
                  value: this.hour[x]
              }
              emit(key, value);
          }
        };

reduce:

var reduce = function(key, value){
          reducedValue = { count: 0, value: 0 };
          for(var i = 0; i < value.length; i++){
              reducedValue.count += value[i].count;
              reducedValue.value += value[i].value;
          }

          return reducedValue;
        };

finalize:

var finalize = function(key, reducedValue){
        reducedValue.average = reducedValue.value/reducedValue.count;

        return reducedValue;
      };

Pretty simple actually.