带查询的MongoDB计数
我一直在做一个项目,现在需要使用MongoDB计数函数(MySQL的等效计数函数)。我现在掌握的密码是带查询的MongoDB计数,mongodb,Mongodb,我一直在做一个项目,现在需要使用MongoDB计数函数(MySQL的等效计数函数)。我现在掌握的密码是 $filter = ["username" => array('$ne' => null, '$ne' => '')]; $options = ["projection" => ['username' => true]]; $query = new MongoDB\Driver\Query($filter, $options); $cursor = $mon
$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查询相同的结果:“从mysqlLog中选择用户名,count(*),其中用户名“”按用户名分组。”。
到目前为止,我所管理的只是where子句,现在我被卡住了。您可以尝试下面的聚合
聚合阶段-$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);
您可以尝试下面的聚合
聚合阶段-$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);
你认为数组('$ne'=>null,$ne'=>'')会返回什么?
会返回列用户名不为null或空字符串的所有字段。这与我的要求不完全一样。哦,对不起!我不知道你的意思。我对MongoDB非常陌生。你认为array(“$ne'=>null,$ne'=>”)返回的是什么?
返回的是列用户名不为null或空字符串的所有字段。这与我的要求不完全一样。哦,对不起!我不知道你的意思。我对MongoDB很陌生。嘿,这似乎很管用!起初没有给我用户名,但我删除了“\u id”=>0,因为我注意到用户名放在那里了。谢谢你的帮助!你知道我如何在给定的时间戳内进行搜索吗?我在前面使用了代码“timestamp”=>array(“$gte”=>intval($startDate),但不确定将其放在这个结构中的什么位置。编辑:我将“['timestamp'=>['$gte'=>intval($startDate)]”在用户名条件之后。非常感谢您的帮助。嘿,这似乎很有效!起初没有给我用户名,但我删除了“_id”=>0,因为我注意到用户名放在那里。感谢您的帮助!知道如何在给定的时间戳内进行搜索吗?我使用了代码“timestamp”=>array(“$gte'=>intval($startDate)之前,但不确定将其放置在此结构中的何处。编辑:我在用户名条件后放置“['timestamp'=>['$gte'=>intval($startDate)]”。非常感谢您的帮助。