开发者

how to do distinct and group in mongodb?

how to do a mysql query SELECT COUNT(DISTINCT ip), COUNT(DISTINCT开发者_如何学Go area) FROM visit_logs GROUP BY t_hour in mongodb without multi mapreduct?


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜