# File lib/statsd/mongo.rb, line 9
    def self.flush_stats(counters, timers)
      raise 'Invalid retention config' if retentions.empty?
      print "#{Time.now} Flushing #{counters.count} counters and #{timers.count} timers to MongoDB"
      stat_string = ''
      time = ::Benchmark.realtime do
        docs = []
        ts = Time.now.to_i
        num_stats = 0        
        retention = retentions.first # always write at the fineset granularity        
        ts_bucket = ts / retention['seconds'].to_i * retention['seconds'].to_i
        
        # connect to store
        db = ::Mongo::Connection.new(hostname).db(database)
        coll = db.collection(retention['name'])

        # store counters
        counters.each_pair do |key,value|
          doc = {:stat => key, :value => value, :ts => ts_bucket, :type => "counter" }
          docs.push(doc)
          counters[key] = 0

          num_stats += 1
        end
    
        # store timers
        timers.each_pair do |key, values|
          if (values.length > 0) 
            pct_threshold = 90
            values.sort!
            count = values.count
            min = values.first
            max = values.last

            mean = min
            max_at_threshold = max

            if (count > 1)
              # strip off the top 100-threshold
              threshold_index = (((100 - pct_threshold) / 100.0) * count).round
              values = values[0..-threshold_index]
              max_at_threshold = values.last

              # average the remaining timings
              sum = values.inject( 0 ) { |s,x| s+x }
              mean = sum / values.count
            end

            timers[key] = []
          
            # Flush Values to Store
            doc = { :stat => key, 
              :values => {
                :mean => mean,
                :max => max,
                :min => min,
                "upper_#{pct_threshold}".to_sym => max_at_threshold,
                :count => count
              },
              :type => "timer",
              :ts => ts_bucket
            }
            docs.push(doc)
          
            num_stats += 1
          end
        end
        coll.insert(docs)
        
       aggregate(ts_bucket)
      end 
      puts "complete. (#{time.round(3)}s)"
    end