如何在mongodb中进行区分和分组? [英] how to do distinct and group in mongodb?
本文介绍了如何在mongodb中进行区分和分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何执行mysql查询 从visit_logs GROUP BY t_hour中选择COUNT(DISTINCT ip个),COUNT(DISTINCT区域) 在没有多mapreduct的mongodb中?
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?
推荐答案
您必须在对象中保留键"列表,并计算作为不同键的计数;这可以在MongoDb的map/reduce中的finalize
方法中完成.
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 };
}
这篇关于如何在mongodb中进行区分和分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文