how to do a mysql query SELECT COUNT(DISTINCT ip), COUNT(DISTINCT area) FROM visit_logs GROUP BY t_hour in mongodb without multi mapreduct?
            Asked
            
        
        
            Active
            
        
            Viewed 3,577 times
        
    3
            
            
        - 
                    what is your collection name and structure of objects in it ? – DhruvPathak Jun 03 '11 at 06:05
1 Answers
7
            
            
        You have to keep the list of "keys" in your objects, and compute your count as the count of the distinct keys; this can be done in the finalize method in MongoDb's map/reduce.
Something like (untested):
var mapFn = function() {
  emit(this.t_hour, { ips: [this.ip], areas: [this.area] );
};
var reduceFn = function(key, values) {
  var ret = { ips: {}, areas: {} };
  // objects used as "sets"
  var ips = {};
  var areas = {};
  values.forEach(function(value) {
    value.ips.forEach(function(ip) {
      if (!ips[ip]) {
        ips[ip] = true; // mark as seen
        ret.ips.push(ip);
      }
    });
    value.areas.forEach(function(area) {
      if (!areas[area]) {
        areas[area] = true; // mark as seen
        ret.areas.push(area);
      }
    });
  });
};
var finalizeFn = function(key, value) {
  return { ips: value.ips.length; areas: value.areas.length };
}
 
    
    
        Thomas Broyer
        
- 64,353
- 7
- 91
- 164
