[英]MongoDB GROUP function (or Map Reduce if necessary) with PHP- Distinct keys
Does anyone have a good way to run a group function in PHP with a DISTINCT count? 有没有人有一个很好的方法来在PHP中以DISTINCT计数运行组函数? 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
What I would like to do is count the UNIQUE userIDs through a group statement by date. 我想做的是按日期通过组语句对UNIQUE用户ID进行计数。 This is the group statement that I am using (in PHP):
这是我正在使用的组语句(在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);
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. 从这一点上来说,我只是在内存中做一个
array_unique
...但是我真正想做的(在网上找不到一个好的答案)是在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. 我看过另外两个例子,我们可以使用一个
array(distinct=>'key')
但我想做一个计数。 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;
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)). 如果确实需要,很高兴在map / reduce中执行此操作-但宁愿找到一种方法将其分组(作为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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.