2017-03-27 73 views
1

我一直在一个项目,现在需要使用MongoDB计数功能(MySQL等值计数功能)。我现在的代码是MongoDB与查询计数

$filter = ["username" => array('$ne' => null, '$ne' => '')]; 

$options = ["projection" => ['username' => true]]; 

$query = new MongoDB\Driver\Query($filter, $options); 

$cursor = $mongo->executeQuery('mongodbLog.logs', $query); 

我想在$ filter数组中添加计数功能,但是我无法使其正常工作。

我想让我的MongoDB查询获得与此MySQL查询相同的结果:“SELECT username,count(*) FROM mysqlLog WHERE username <> '' GROUP BY username”。 到目前为止我所管理的所有东西都是where子句的等价物,现在我被卡住了。

+2

你觉得呢'阵列( '$ NE'=> NULL, '$ NE'=> '')'的回报? – styvane

+0

这将返回列用户名不为空或空字符串的所有字段。 – heatonhampus

+1

不是我所问的。 http://ideone.com/vBkUgj – styvane

回答

0

您可以尝试下面的聚合。

聚合平台 - $match - $group - $project

$pipeline = 
     [ 
      [ 
       '$match' => 
        [ 
        '$and' => 
         [ 
          ['username' => ['$ne' => null]], 
          ['username' => ['$ne' => '']], 
         ], 
        ], 
      ], 
      [ 
       '$group' => 
        [ 
         '_id' => '$username', 
         'count' => ['$sum' => 1], 
        ], 
      ], 
      [ 
       '$project' => 
        [ 
         '_id' => 0, 
         'username' => 1, 
         'count' => 1, 
        ], 
      ], 
     ]; 

    $command = new \MongoDB\Driver\Command([ 
     'aggregate' => 'logs', 
     'pipeline' => $pipeline 
     ]); 

    $cursor = $mongo->executeCommand('mongodbLog', $command); 
+0

嘿,这似乎是诀窍!最初没有给我用户名,但是我删除了'_id'=> 0,因为我注意到用户名被放在那里。谢谢你的帮助!任何想法如何包括在给定的时间戳内搜索?我已经使用过代码“timestamp”=> array('$ gte'=> intval($ startDate)),但是不知道把它放在这个结构中的哪个位置 编辑:我把“['timestamp'=> '$ gte'=> intval($ startDate)]],“在用户名条件之后。非常感谢您的帮助。 – heatonhampus