MongoDB计入查询

时间:2017-03-27 08:45:34

标签: mongodb

我一直在研究一个现在需要使用MongoDB计数功能的项目(MySQL等效的计数功能)。我目前的代码是

$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查询相同的结果:&#34; SELECT username,count(*) FROM mysqlLog WHERE username <> '' GROUP BY username&#34;。 到目前为止我所管理的只是where子句等同于现在我被卡住了。

1 个答案:

答案 0 :(得分: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);