具有PHP独特键的MongoDB GROUP函数(或在必要时使用Map Reduce) [英] MongoDB GROUP function (or Map Reduce if necessary) with PHP- Distinct keys
问题描述
有人在用DISTINCT计数在PHP中运行组函数的好方法吗?情况是这样的:我想检查到我们应用程序的唯一登录名.这就是我要查询的当前集合中的文档的样子:
Does anyone have a good way to run a group function in PHP with a DISTINCT count? The situation is this: I want to check unique logins to our app. This is how the document in the current collection I'm querying looks like:
Array
(
[_id] => MongoId Object
(
[$id] => 50f6da87686ba9f449000003
)
[userId] => 50f6bd0f686ba91a4000000f
[action] => login
[time] => 1358355079
我想做的是通过组语句按日期对UNIQUE用户ID进行计数.这是我正在使用的组语句(在PHP中):
What I would like to do is count the UNIQUE userIDs through a group statement by date. This is the group statement that I am using (in PHP):
$map= new MongoCode('function(frequency) {
var date = new Date(Number(frequency.time) * 1000 - (8 * 3600000));
var dd = date.getDate();
var yyyy = date.getFullYear();
var mm = date.getMonth() + 1;
if(dd<10){dd="0"+dd}
if(mm<10){mm="0"+mm}
var transday = yyyy + "-"+ mm + "-" + dd;
return{"date": transday}
}');
$initial = array('logins' => array());
$reduce = "function(obj, prev){
prev.logins.push(obj.userId);
}";
try{
$distinct = array();
$g = $this->_bingomongo->selectCollection("UserLog")->group($map, $initial, $reduce);
从这一点上来说,我只是在内存中做一个array_unique
...但是我真正想做的(在网上找不到好的答案)是按.我看到了另外两个可以使用array(distinct=>'key')
的示例,但我希望进行计数.有什么想法吗?
From this point I am simply doing an array_unique
in memory...but what I'd really like to do (and can't find a good answer on the net) is run a distinct count in the group by. I have seen a couple of other examples where we can use an array(distinct=>'key')
but I am looking to do a count. Any thoughts?
以下是当前(不完美)格式的其余代码:
Here's the rest of the code in it's current (imperfect) format:
foreach($g['retval'] as $k=>$v) {
$distinct[date('m.d', strtotime($v['date']))] = array_unique($v['logins']);
}
}
catch(Exception $e) {
return $e;
} return $g;
很乐意在必要时在map/reduce中执行此操作-但宁愿找到一种方法将其分组(作为COUNT(distinct)).
Happy to do this in map/reduce if strictly necessary- but would rather find a way to keep it in group by (as a COUNT(distinct)).
推荐答案
您应该可以执行以下操作:
You should be able to do something like this:
...
$initial = array('logins' => array());
$reduce = "function(obj, prev){
prev.logins[obj.userId] = 1;
}";
$finalize = "function(result) {
result.loginList = Object.keys(result.logins);
result.count = result.loginList.length;
}";
try{
$distinct = array();
$g = $this->_bingomongo->selectCollection("UserLog")->group(
$map, $initial, $reduce, array('finalize'=>$finalize));
这篇关于具有PHP独特键的MongoDB GROUP函数(或在必要时使用Map Reduce)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!