如何在mongodb中做出明显的分组?

时间:2011-06-03 03:56:53

标签: mongodb mapreduce

如何进行mysql查询 SELECT COUNT(DISTINCT ip),COUNT(DISTINCT区域)来自visit_logs GROUP BY t_hour 在没有多mapreduct的mongodb?

1 个答案:

答案 0 :(得分:7)

您必须在对象中保留“键”列表,并将计数计算为不同键的计数;这可以在MongoDb map / reduce中的finalize方法中完成。

像(未经测试)的东西:

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 };
}