MongoDB GROUP function (or Map Reduce if necessary

2019-08-18 09:25发布

问题:

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

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

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;

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)).

回答1:

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